Given a map (e.g. word -> count), produce the entries ordered by value ascending or descending.
A hash map is unordered, so extract the entries, sort them by value with a comparator (reversed for descending, with a tie-break on the key), and collect into an insertion-ordered structure. The common mistake is expecting the hash map itself to become sorted. O(k log k).
public static Map<String,Integer> sortByValueDesc(Map<String,Integer> map) {
return map.entrySet().stream()
.sorted(Map.Entry.<String,Integer>comparingByValue().reversed())
.collect(java.util.stream.Collectors.toMap(
Map.Entry::getKey, Map.Entry::getValue,
(a, b) -> a, LinkedHashMap::new));
}function sortByValueDesc(obj) {
return Object.entries(obj)
.sort((a, b) => b[1] - a[1])
.reduce((acc, [k, v]) => (acc[k] = v, acc), {});
}def sort_by_value_desc(d):
return dict(sorted(d.items(), key=lambda kv: kv[1], reverse=True))The natural follow-up to frequency counting: "show the top 5 most common failures" — sort a frequency map by value descending.
A candidate sorts the entries then puts them back into a HashMap and the order is lost. Fix?