Map Entry ComparingByValue Sort

Sort map entries by value with Map.Entry.comparingByValue, then chain thenComparing(comparingByKey) so tied values keep a stable order.

JavaData Integrity

Code

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

public class MapEntrySortByValue {

    public static void main(String[] args) {
        Map<String, Integer> visits = new LinkedHashMap<>();
        visits.put("cart", 3);
        visits.put("home", 9);
        visits.put("search", 5);

        // Entry.comparingByValue:按值排序;值互不相同时结果唯一
        visits.entrySet().stream()
                .sorted(Map.Entry.<String, Integer>comparingByValue().reversed())
                .forEach(entry -> System.out.println("top pages: " + entry));

        // 值并列时 HashMap 遍历顺序随机:必须补键名次级排序输出才稳定
        Map<String, Integer> withTies = new HashMap<>();
        withTies.put("home", 9);
        withTies.put("search", 5);
        withTies.put("api", 5);
        withTies.put("cart", 3);
        Map<String, Integer> ranked = withTies.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));
        System.out.println("ranked map: " + ranked);
    }
}

How it works

Map Entry ComparingByValue Sort is built around the class MapEntrySortByValue and the function main.

The transformation runs as a stream pipeline — source, intermediate operations, terminal collector — so each stage stays independently readable.

Caveats

  • Behavior originates in the standard library alone — no external surface.

Putting it to use

Signature: public static void main(String[] args)

Each run prints the 2 labeled blocks top pages:, ranked map: in source order.

Core lines

.collect(Collectors.toMap(
        Map.Entry::getKey,
        Map.Entry::getValue,
        (a, b) -> a,
        LinkedHashMap::new));
visits.entrySet().stream()
        .sorted(Map.Entry.<String, Integer>comparingByValue().reversed())
        .forEach(entry -> System.out.println("top pages: " + entry));

Interactive Tools for This Topic

FAQ

What does Map Entry ComparingByValue Sort print when run?
The script runs standalone; its 2 labeled outputs include `top pages:`, `ranked map:`.