Video in progress

Strong Middle 🌊 Streams and lambdas

How do you count word frequencies and print the top 10 most frequent in descending order?

First build a Map<String, Long> with groupingBy(identity(), counting()), then sort entrySet().stream() by Map.Entry.comparingByValue().reversed() and limit(10). To preserve the result order you have to collect into a LinkedHashMap: a plain toMap gives a HashMap and the order is lost.

📖 Answer

Map<String, Long> freq = Arrays.stream(text.toLowerCase().split("\\W+"))
        .filter(w -> !w.isBlank())
        .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

Map<String, Long> top10 = freq.entrySet().stream()
        .sorted(Map.Entry.<String, Long>comparingByValue().reversed()
                .thenComparing(Map.Entry.comparingByKey()))
        .limit(10)
        .collect(Collectors.toMap(
                Map.Entry::getKey,
                Map.Entry::getValue,
                (a, b) -> a,
                LinkedHashMap::new));

A few subtle points:

  • Map.Entry.<String, Long>comparingByValue(): you have to write the type arguments explicitly, otherwise in a chain with .reversed() the compiler can't infer the type.
  • thenComparing(comparingByKey()): so that words with equal frequency come out the same on every run. Without it the result depends on HashMap order and tests become flaky.
  • The merge function (a, b) -> a is never called here (the keys are unique), but it's required for the four-argument variant of toMap.
  • If you need the result only as a list, map(e -> e.getKey() + "=" + e.getValue()).toList() is simpler.

If the volume is large (millions of unique words), sorting the whole entrySet is wasteful: a PriorityQueue of size 10 is better there. If the data is in a database, use GROUP BY ... ORDER BY count DESC LIMIT 10.