Last active
March 18, 2018 23:32
-
-
Save shailrshah/a4c3068a2f8baa7eb365ef1f4db732db to your computer and use it in GitHub Desktop.
Sort a Map by value(descending) and then key(ascending)
This file contains hidden or 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
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