user2634655
user2634655

Reputation:

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);
}

Upvotes: 1

Views: 69

Answers (2)

Stephen C
Stephen C

Reputation: 718788

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.

Upvotes: 0

JB Nizet
JB Nizet

Reputation: 691715

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());
    }
});

Upvotes: 4

Related Questions