Skip to content

Instantly share code, notes, and snippets.

@gabrielstelmach
Created December 5, 2017 19:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gabrielstelmach/3e9860ea3ae84793c97680c2571589b1 to your computer and use it in GitHub Desktop.
Save gabrielstelmach/3e9860ea3ae84793c97680c2571589b1 to your computer and use it in GitHub Desktop.
Sorting entries of Map by entry value
/**
* 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