Map.Entry.comparingByValue gives a ready-made comparator, and LinkedHashMap preserves the order the stream produced.
Map<String, Integer> sales = new HashMap<>();
sales.put("north", 300);
sales.put("south", 900);
sales.put("east", 150);
LinkedHashMap<String, Integer> topFirst = sales.entrySet().stream()
.sorted(Map.Entry.<String, Integer>comparingByValue().reversed())
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
(a, b) -> a, LinkedHashMap::new));
topFirst.forEach((region, amount) -> System.out.println(region + " " + amount));
south 900
north 300
east 150
Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.
Published 2026-07-30