Java: Sort a Map by value using streams

Stream the entry set, sort by value, and collect into a LinkedHashMap to keep order.

Code
Map<String, Integer> scores = Map.of("Ava", 90, "Ben", 75, "Cara", 88);
scores.entrySet().stream()
        .sorted(Map.Entry.<String, Integer>comparingByValue().reversed())
        .forEach(e -> System.out.println(e.getKey() + "=" + e.getValue()));
Output
Ava=90
Cara=88
Ben=75
Advertisement

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-26