简体   繁体   中英

order a hash map by the size of it's values. java

This hash map uses as a key a string object called Sentence, which is an important part of the program that can't be changed. The data should be organized according to the size of the corresponding value, which is an integer, with the largest coming first and descending to the lowest values, 1 would be the minimum bound, amongst each partition ordering is not important. Is that possible to achieve that using this code?

//map to store learned 'rules'
Map<Sentence, Integer> ruleCount = new HashMap<>();
//store data
public void numberRules(Sentence sentence) 
{
    if (!ruleCount.containsKey(sentence))
    {
        ruleCount.put(sentence, 0);
    }
    ruleCount.put(sentence, ruleCount.get(sentence) + 1);
}

A HashMap has no order. There are sorted maps, but they're sorted by keys, not values. Just transform your map to a List when you're done modifying it, and sort the list:

List<Map.Entry<Sentence, Integer>> entries = new ArrayList<>(ruleCount.entrySet());
Collections.sort(entries, new Comparator<Map.Entry<Sentence, Integer>>() {
    @Override
    public int compare(Map.Entry<Sentence, Integer> e1, Map.Entry<Sentence, Integer> e2) {
        return e1.getValue().compareTo(e2.getValue());
    }
});

You can't do this with (just) a Map. Maps don't order their entries by value.

One possible solution would be to copy the map's entries into an array, and then sort the array. But that is expensive if you need sort repeatedly.

Another approach would be to create data structure that is (in effect) a Map<Sentence, Record> combined with a TreeSet<Record> . The Record has a mutable int count field and an immutable Sentence field. The TreeSet is ordered by count, and when you update a count you need to remove and reinsert the Record .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM