Skip to content

Instantly share code, notes, and snippets.

@shailrshah
Last active March 18, 2018 23:32
Show Gist options
  • Save shailrshah/a4c3068a2f8baa7eb365ef1f4db732db to your computer and use it in GitHub Desktop.
Save shailrshah/a4c3068a2f8baa7eb365ef1f4db732db to your computer and use it in GitHub Desktop.
Sort a Map by value(descending) and then key(ascending)
private static <K extends Comparable<K>, V extends Comparable<V>>Map<K, V> sortMap(Map<K, V> map) {
List<Map.Entry<K, V>> entries = mapToEntries(map);
sortEntries(entries);
return entriesToMap(entries);
}
private static <K extends Comparable<K>, V extends Comparable<V>> List<Map.Entry<K,V>> mapToEntries(Map<K, V> map) {
return new ArrayList<>(map.entrySet());
}
private static <K extends Comparable<K>, V extends Comparable<V>>void sortEntries(List<Map.Entry<K, V>> entries) {
entries.sort((o1, o2) -> {
int byKeyAsc = o1.getKey().compareTo(o2.getKey());
int byKeyDesc = o2.getKey().compareTo(o1.getKey());
int byValAsc = o1.getValue().compareTo(o2.getValue());
int byValDesc = o2.getValue().compareTo(o1.getValue());
return byValDesc != 0 ? byValDesc : byKeyAsc; // value(desc), key(asc)
});
}
private static <K extends Comparable<K>, V extends Comparable<V>> Map<K,V> entriesToMap(List<Map.Entry<K, V>> entries) {
Map<K, V> map = new LinkedHashMap<>();
entries.forEach(entry -> map.put(entry.getKey(), entry.getValue()));
return map;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment