Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Possible Duplicate:
How to sort a Map<Key, Value> on the values in Java?

I have a HashMap of the type:

HashMap<String, Integer> h = new HashMap<String, Integer>();

The HashMap contains a list of Strings and the Integer is a counter for the number of times that String has been found. What I would like to be able to do is sort the HashMap based on the Integers, then on the alphabetical order of the Strings.

At the moment I am keeping a record of the largest occurrence of a word (variable named max) and displaying the values as follows:

public void print(){
    while(max > 0){
       for (String key : h.keySet()){
           if(h.get(key) == max){
               System.out.println(key + " " + h.get(key));
           }
       }
       max--;
    }
}

Which doesn't sort the values alphabetically, also it accesses the HashMap max*h(size) times.

What is the better solution?

like image 780
neut Avatar asked Jun 19 '10 03:06

neut


People also ask

How do you sort HashMap by value and then key?

The idea is to put all data of HashMap into an ArrayList. Then extract all the keys of HashMap into an ArrayList. Next, sort the extracted keys using the Collections. sort() method, and then for each key extract its value using the get() method.

Can you sort a HashMap based on values?

Key and Value can be of different types (eg - String, Integer). We can sort the entries in a HashMap according to keys as well as values.

Does HashMap overwrite duplicate keys?

HashMap stores key, value pairs and it does not allow duplicate keys. If the key is duplicate then the old key is replaced with the new value.

Does map sort by key or value?

No two mapped values can have equal key values. By default, a Map in C++ is sorted in increasing order based on its key.


1 Answers

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>());
like image 125
Sean Avatar answered Oct 23 '22 12:10

Sean