The 30 second answer
A HashMap has no order, so I stream its entrySet, sort the entries with Map.Entry.comparingByValue, and collect with the four-argument toMap into a LinkedHashMap so the sorted order survives. The merge function is never called because keys are already unique, but toMap needs it to accept a map supplier. For ties I add a second key comparison, usually by key.
var scores = Map.of("ann", 72, "bob", 95, "cid", 72, "dee", 88);
var byScoreAsc = scores.entrySet().stream()
.sorted(Map.Entry.comparingByValue())
.collect(Collectors.toMap(
Map.Entry::getKey,
Map.Entry::getValue,
(first, second) -> first,
LinkedHashMap::new));
// Highest score first, ties broken by name:
var byScoreDesc = scores.entrySet().stream()
.sorted((a, b) -> {
int byValue = Integer.compare(b.getValue(), a.getValue());
return byValue != 0 ? byValue : a.getKey().compareTo(b.getKey());
})
.collect(Collectors.toMap(
Map.Entry::getKey,
Map.Entry::getValue,
(first, second) -> first,
LinkedHashMap::new));
// {bob=95, dee=88, ann=72, cid=72}Why LinkedHashMap: the two-argument toMap gives no guarantee on the map type, so the order you sorted into is lost. LinkedHashMap keeps insertion order, and you insert in sorted order. Only the four-argument toMap takes a map supplier, which is why a merge function is passed even though keys from a map cannot collide.
Descending: Map.Entry.comparingByValue(Comparator.reverseOrder()) works on its own. Chaining .thenComparing(Map.Entry.comparingByKey()) onto it does not compile without explicit type arguments, because the compiler cannot infer the entry types for the first call. The explicit lambda above avoids that and keeps generics out of the code.
Complexity: O(n log n) time for the sort and O(n) space for the new map.
Edge cases: ties need a rule, or their order depends on the source map's iteration order. Map.of and HashMap do not define that order. A null value throws in comparingByValue and in toMap. If they want the top k only, add limit(k) after sorted.
What interviewers listen for: that you know a HashMap cannot be sorted in place, that you return a LinkedHashMap, and that you can explain the merge function. A TreeMap sorts by key, not value, so it is the wrong tool here.
Sources (3)
- Map.Entry.comparingByValue and comparingByKeydocs.oracle.com
- Collectors.toMap with mapFactorydocs.oracle.com
- LinkedHashMap (insertion order)docs.oracle.com