HashMap has a convenient method called entrySet(), which lets you access a collection of key-value pairs. You can use it to construct a List<Map.Entry<String,Integer>>.
Now you have something you can sort. Use a sort method with a custom comparator, which orders entries with higher frequencies toward the beginning of the list.
With a sorted list in hand, all you need to do is walk it, and harvest the words which are now in the proper order.
List<Map.Entry<String,Integer>> entries = new ArrayList<Map.Entry<String,Integer>>(
freqMap.entrySet()
);
Collections.sort(
entries
, new Comparator<Map.Entry<String,Integer>>() {
public int compare(Map.Entry<String,Integer> a, Map.Entry<String,Integer> b) {
return Integer.compare(b.getValue(), a.getValue());
}
}
);
for (Map.Entry<String,Integer> e : entries) {
// This loop prints entries. You can use the same loop
// to get the keys from entries, and add it to your target list.
System.out.println(e.getKey()+":"+e.getValue());
}
Demo.
Wordthat holds theStringand the frequency and implements theComparableinterface comparingWordobjects by their frequency. Then populate anArrayList<Word>from theHashMapand then callCollections.sort(yourArrayList)Map<String, Integer>I've used anArrayList<MyClass>, whereMyClasscontains theString wordandint/double frequency. You can then use theCollections.sort(yourList, new Comparator<MyClass>(){ @Override public int compare(MyClass mc1, MyClass mc2){ ... } });to sort itHashMapinto aTreeMap, sorting it using acomparatorthen iterating over the elements and loading into anArrayList?