Tech Interview RoomStudy guides

Java Streams

Sort a HashMap by its values. Compare a list of entries, TreeMap with a comparator, streams into a LinkedHashMap and Java 21 sequenced maps.

Intermediate · 2 min read · Lesson 3 of 4 in Java Streams

Problem

Given word counts {apple=3, banana=1, cherry=3, date=2}, produce them ordered by count descending, ties alphabetical. A top-5 most asked Java collections question.

Pattern

A HashMap has no order, so you must copy entries into an ordered structure: a sorted list, or a LinkedHashMap filled in sorted order.

Approach 1: Sort a list of entries with a Comparator (Java 7/8)

java
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

class SortByValueList {
    static Map<String, Integer> sort(Map<String, Integer> map) {
        List<Map.Entry<String, Integer>> entries = new ArrayList<>(map.entrySet());
        entries.sort(Map.Entry.<String, Integer>comparingByValue().reversed().thenComparing(Map.Entry.comparingByKey()));
        Map<String, Integer> result = new LinkedHashMap<>();
        for (Map.Entry<String, Integer> e : entries) result.put(e.getKey(), e.getValue());
        return result;
    }
}

Approach 2: TreeMap with a value comparator (a common trap)

A comparator that compares values makes keys with equal values look like the same key, so entries vanish; and lookups by key break. Breaking ties by key fixes the vanishing but the map is still fragile if values change.

java
import java.util.Map;
import java.util.TreeMap;

class SortByValueTreeMap {
    static Map<String, Integer> broken(Map<String, Integer> map) {
        Map<String, Integer> sorted = new TreeMap<>((a, b) -> map.get(b).compareTo(map.get(a)));   // ties collapse!
        sorted.putAll(map);
        return sorted;
    }
    static Map<String, Integer> fixed(Map<String, Integer> map) {
        Map<String, Integer> sorted = new TreeMap<>((a, b) -> {
            int byValue = map.get(b).compareTo(map.get(a));
            return byValue != 0 ? byValue : a.compareTo(b);
        });
        sorted.putAll(map);
        return sorted;
    }
}

Approach 3: Streams collected into a LinkedHashMap (Java 8) — idiomatic

java
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.stream.Collectors;

class SortByValueStreams {
    static Map<String, Integer> sort(Map<String, Integer> map) {
        return map.entrySet().stream()
            .sorted(Map.Entry.<String, Integer>comparingByValue().reversed().thenComparing(Map.Entry.comparingByKey()))
            .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (a, b) -> a, LinkedHashMap::new));
    }
}

Approach 4: Java 21 SequencedMap: top and bottom entries directly

java
import java.util.Map;
import java.util.SequencedMap;

class SortByValueJava21 {
    static String describe(Map<String, Integer> map) {
        SequencedMap<String, Integer> sorted = (SequencedMap<String, Integer>) SortByValueStreams.sort(map);
        return "top=" + sorted.firstEntry() + " bottom=" + sorted.lastEntry() + " ascending=" + sorted.reversed();
    }
}

class SortByValueDemo {
    public static void main(String[] args) {
        Map<String, Integer> counts = new java.util.HashMap<>(Map.of("apple", 3, "banana", 1, "cherry", 3, "date", 2));
        System.out.println(SortByValueList.sort(counts));           // {apple=3, cherry=3, date=2, banana=1}
        System.out.println(SortByValueTreeMap.broken(counts));      // only one of apple/cherry survives
        System.out.println(SortByValueTreeMap.fixed(counts));       // {apple=3, cherry=3, date=2, banana=1}
        System.out.println(SortByValueStreams.sort(counts));        // {apple=3, cherry=3, date=2, banana=1}
        System.out.println(SortByValueJava21.describe(counts));     // top=apple=3 bottom=banana=1 ascending={banana=1, date=2, cherry=3, apple=3}
    }
}

Feasible → optimal

All are O(n log n). The list-of-entries and streams versions are correct and clear (streams is the idiomatic answer); the value-comparing TreeMap is the trap interviewers look for; Java 21's SequencedMap gives first/last and reversed views without extra code. For "top K by value" over a huge map, a size-K heap is O(n log K).

Follow-up questions interviewers ask

Try answering each one before you open it.

Related (same pattern): find the top 3 most frequent words in a text.

groupingBy(identity, counting()) then sort entries by value descending (ties by key) and limit(3); or a min-heap of size 3 for very large vocabularies (see Top K Frequent Elements).

Related (same pattern): sort a list of employees by salary then name, or sort a map by key in reverse.

list.sort(comparing(Employee::salary).reversed().thenComparing(Employee::name)); for keys, new TreeMap<>(Comparator.reverseOrder()) with putAll, or map.entrySet().stream().sorted(Map.Entry.comparingByKey(Comparator.reverseOrder())).