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

  1. Get entrySet() from map
  2. Sort using Comparator
  3. Compare by entry.getValue()

Related Collections exercises

Practice all Collections exercises · Run this idea in the Java compiler