Created
December 5, 2017 19:43
-
-
Save gabrielstelmach/3e9860ea3ae84793c97680c2571589b1 to your computer and use it in GitHub Desktop.
Sorting entries of Map by entry value
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
/** | |
* Orders the map entries by value. | |
* | |
* @param map Map with entries to be ordered. | |
* @return Map ordered by its value. | |
*/ | |
public static <K, V extends Comparable<? super V>> LinkedHashMap<String, String> orderedMapByValues(Map<K, V> map) | |
{ | |
SortedSet<Map.Entry<K, V>> orderedEntries = new TreeSet<Map.Entry<K, V>>(new Comparator<Map.Entry<K, V>>() | |
{ | |
@Override | |
public int compare(Map.Entry<K, V> e1, Map.Entry<K, V> e2) | |
{ | |
int result = e1.getValue().compareTo(e2.getValue()); | |
return ((result != 0) ? result : 1); | |
} | |
} | |
); | |
orderedEntries.addAll(map.entrySet()); | |
LinkedHashMap<String, String> orderedMap = new LinkedHashMap<String, String>(orderedEntries.size()); | |
for (Map.Entry <K, V> entry : orderedEntries) | |
{ | |
orderedMap.put(entry.getKey().toString(), entry.getValue().toString()); | |
} | |
return orderedMap; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment