Sorting a HashMap based on Value then Key? [duplicate]

戏子无情 提交于 2019-11-29 04:33:33

Here's a Comparator that sorts Map.Entry objects with Comparable keys and values:

public class ValueThenKeyComparator<K extends Comparable<? super K>,
                                    V extends Comparable<? super V>>
    implements Comparator<Map.Entry<K, V>> {

    public int compare(Map.Entry<K, V> a, Map.Entry<K, V> b) {
        int cmp1 = a.getValue().compareTo(b.getValue());
        if (cmp1 != 0) {
            return cmp1;
        } else {
            return a.getKey().compareTo(b.getKey());
        }
    }

}

You'd put all of the map entries into a list and then sort that:

List<Map.Entry<String, Integer>> list = new ArrayList<Map.Entry<String, Integer>>(h.entrySet());
Collections.sort(list, new ValueThenKeyComparator<String, Integer>());
Aravind R. Yarram

Look at Google Guava libraries. It has a Multiset which does the calculation for you and then you have Ordering class that simplifies sorting.

All you need to do is to populate Multiset with your strings. It will maintain the frequency for you. Then you can sort on those strings using Ordering.

Probably not the most elegant solution, but how about this?

//TreeSet with reversed natural ordering (big integers first)
Map<Integer, Set<String>> h = 
     new TreeMap<Integer, Set<String>>(Collections.reverseOrder());
//and use TreeSet for the set...
// ...    
// 
for(Map.Entry<Integer,Set<String>> entry : h.entrySet()){
    for(String str : entry.getValue()){
        System.out.println(str + " has occured " + entry.getKey() + " times.");
    }
}

you can use SortedMap interface to sort your HashMap. It's very easy - Automatic sorting. Refer to http://java.sun.com/j2se/1.4.2/docs/api/java/util/SortedMap.html. I didn't include any code here, but if you need, just add a comment. I'll give you a sample code.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!