Sort Map by Value in Java: Explanation & Practice
Sort a map by its values
Problem summary
Write a program that sorts a Map by its values in descending order.
Starter code
import java.util.*;
public class Main {
public static void main(String[] args) {
Map<String, Integer> scores = new HashMap<>();
scores.put("Alice", 85);
scores.put("Bob", 92);
scores.put("Carol", 78); // Test case 1
// Sort by score (descending)
// Print: name: score
}
}Expected output and test cases
- Sorted by score
Bob: 92 Alice: 85 Carol: 78
- Different scores
A: 100 B: 90 C: 80
- Single entry
X: 50
Hints
- Get entrySet() from map
- Sort using Comparator
- Compare by entry.getValue()
Related Collections exercises
- Practice Remove Duplicates from List in Java
- Practice List Intersection in Java
- Practice Group By Property in Java
Practice all Collections exercises · Run this idea in the Java compiler