I have the following HashMap
:
HashMap<String, Integer> counts = new HashMap<String, Integer>();
What is the simplest way to order it according to the values?
I have the following HashMap
:
HashMap<String, Integer> counts = new HashMap<String, Integer>();
What is the simplest way to order it according to the values?
You can't sort a Map
by the values, especially not a HashMap
, which can't be sorted at all.
Instead, you can sort the entries:
List<Map.Entry<String, Integer>> entries = new ArrayList<Map.Entry<String, Integer>>(map.entrySet());
Collections.sort(entries, new Comparator<Map.Entry<String, Integer>>() {
public int compare(
Map.Entry<String, Integer> entry1, Map.Entry<String, Integer> entry2) {
return entry1.getValue().compareTo(entry2.getValue());
}
});
will sort the entries in ascending order of count.
You can get a set of entries (Set
of Map.Entry
) from a map, by using map.entrySet()
. Just iterate over them, and check the values by getValue()
.
A work around, if you want to them print them in order(Not storing).
Create a new Map (tempMap
) and put your value as key and key as value. To make the keys unique, please add some unique value in each of the keys e.g. key1 = value1+@0.
Get the list of values as map.values()
as list myVlues
Sort the myVlues
list as Collections.sort(myVlues)
Now iterate the myVlues
, get the corresponding key
from tempMap
, restore the key e.g. key.substring(0, key.length-2) and print the key and value pair.
Hope this helps.
A TreeMap can keep its entries in an order defined by a Comparator.
counts
map into the Comparator.Finally, we will get the first key in the map, which should be the most common word (or at least one of them, if multiple words have equal counts).
public class Testing {
public static void main(String[] args) {
HashMap<String,Double> counts = new HashMap<String,Integer>();
// Sample word counts
counts.put("the", 100);
counts.put("pineapple",5);
counts.put("a", 50);
// Step 1: Create a Comparator that order by value with greatest value first
MostCommonValueFirst mostCommonValueFirst = new MostCommonValueFirst(counts);
// Step 2: Build a TreeMap that uses that Comparator
TreeMap<String,Double> sortedMap = new TreeMap<String,Integer (mostCommonValueFirst);
// Step 3: Populate TreeMap with values from the counts map
sortedMap.putAll(counts);
// Step 4: The first key in the map is the most commonly used word
System.out.println("Most common word: " + sortedMap.firstKey());
}
}
private class MostCommonValueFirst implements Comparator<String> {
Map<String, Integer> base;
public MostCommonValueFirst(Map<String, Integer> base) {
this.base = base;
}
// Note: this comparator imposes orderings that are inconsistent with equals.
public int compare(String a, String b) {
if (base.get(a) >= base.get(b)) {
return 1;
} else {
return -1;
} // returning 0 would merge keys
}
}