Skip to content

Instantly share code, notes, and snippets.

@milindjagre
Created December 17, 2018 20:27
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save milindjagre/792ffcfbe116ead0c52f998a36d86281 to your computer and use it in GitHub Desktop.
This method returns the HashMap which is sorted by Values.
public static LinkedHashMap<String, Integer> sortHashMapByValues(
Map<String, Integer> wordCountMap) {
List<String> mapKeys = new ArrayList<String>(wordCountMap.keySet());
List<Integer> mapValues = new ArrayList<Integer>(wordCountMap.values());
Collections.sort(mapValues, Collections.reverseOrder());
Collections.sort(mapKeys);
LinkedHashMap<String, Integer> sortedMap = new LinkedHashMap<String, Integer>();
Iterator<Integer> valueIt = mapValues.iterator();
while (valueIt.hasNext()) {
Integer val = valueIt.next();
Iterator<String> keyIt = mapKeys.iterator();
while (keyIt.hasNext()) {
String key = keyIt.next();
Integer comp1 = wordCountMap.get(key);
Integer comp2 = val;
if (comp1.equals(comp2)) {
keyIt.remove();
sortedMap.put(key, val);
break;
}
}
}
return sortedMap;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment