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?
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.
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.
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.
No two mapped values can have equal key values. By default, a Map in C++ is sorted in increasing order based on its key.
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>());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With