Created
December 17, 2018 20:27
Star
You must be signed in to star a gist
This method returns the HashMap which is sorted by Values.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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