A small puzzle came up during a pairing session:

Take a list of IDs. What do you get if you multiply together the three IDs that appear most often?

It's a one-liner in spirit, and Java streams look like the obvious tool. Getting to a version I'm happy with took a few rounds, though. Along the way I noticed that my "single stream" was actually two streams, tried to fix that with a Gatherer, decided against it, and ended up with a small hybrid that reads like the problem statement. This post follows that path and ends with what I took away about stream limitations and where Gatherers really belong.

How to run the examples

Every example below is a complete, self-contained Java file with all imports and a main method. Save it as TopIdProduct.java and run it directly with the single-file source launcher. No build tool or separate javac step is needed:

java TopIdProduct.java 

You need Java 25 (the current LTS). Only the Gatherer examples actually require it; the rest also run on Java 17+.

If you'd rather not install anything, there are two browser options:

  • ▶ Try it on JBang. Every example has a link under it that opens JBang's try page with the code already in the editor. Click run and it executes on Java 25. The first run can take half a minute, because the page starts a free MyBinder backend.
  • Oracle's Java Playground. This is the official playground on dev.java, and it runs the latest Java (with preview features). It has no links with the code in them, so copy and paste the example into the editor yourself.

Both run Java in the style of JShell: a pasted class is only defined, and its main method isn't called. The JBang links already include the extra line. When you paste into the Java Playground, add a call to main at the end yourself, for example:

TopIdProduct.main(new String[0]); 

All examples use the same sample data:

7, 3, 7, 5, 3, 7, 9, 5, 3, 2 

7 and 3 appear three times each and 5 twice, so the answer is 7 × 3 × 5 = 105.

Step 1: The pure stream solution

The first version is a classic stream pipeline. Count each ID, sort by count, take three, multiply:

import java.math.BigInteger; import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.function.Function; import java.util.stream.Collectors; public class TopIdProduct { public static BigInteger productOfTop3(List<Long> ids) { return ids.stream() .collect(Collectors.groupingBy(Function.identity(), Collectors.counting())) .entrySet().stream() .sorted(Map.Entry.<Long, Long>comparingByValue(Comparator.reverseOrder()) .thenComparing(Map.Entry.comparingByKey())) // tie-break: smaller ID wins .limit(3) .map(e -> BigInteger.valueOf(e.getKey())) .reduce(BigInteger.ONE, BigInteger::multiply); } public static void main(String[] args) { List<Long> ids = List.of(7L, 3L, 7L, 5L, 3L, 7L, 9L, 5L, 3L, 2L); System.out.println(productOfTop3(ids)); // 105 } } 

▶ Try it on JBang

A few details are worth pointing out before moving on:

  • BigInteger for the product. Three large long IDs can easily overflow a long when multiplied.
  • An explicit tie-break. The question says "the three most frequent", but it doesn't say what happens when several IDs share third place. Here the smaller ID wins. That's a business decision, so the code should make it visible rather than leave it to HashMap iteration order.
  • The comparator is the ugliest line. Map.Entry.<Long, Long>comparingByValue(...) needs the explicit type witness, because Java can't infer the types through the chained thenComparing call.

Step 2: Naming things

The first refactoring step is purely about readability. I moved the comparator and the collector into named methods:

import java.math.BigInteger; import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.function.Function; import java.util.stream.Collector; import java.util.stream.Collectors; public class TopIdProduct { public static BigInteger productOfTop3(List<Long> ids) { return ids.stream() .collect(countingFrequency()) .entrySet().stream() .sorted(byFrequencyDescThenIdAsc()) .limit(3) .map(e -> BigInteger.valueOf(e.getKey())) .reduce(BigInteger.ONE, BigInteger::multiply); } private static <T> Collector<T, ?, Map<T, Long>> countingFrequency() { return Collectors.groupingBy(Function.identity(), Collectors.counting()); } private static Comparator<Entry<Long, Long>> byFrequencyDescThenIdAsc() { return Entry.<Long, Long>comparingByValue(Comparator.reverseOrder()) .thenComparing(Entry.comparingByKey()); } public static void main(String[] args) { List<Long> ids = List.of(7L, 3L, 7L, 5L, 3L, 7L, 9L, 5L, 3L, 2L); System.out.println(productOfTop3(ids)); // 105 } } 

▶ Try it on JBang

The method's return type tells the compiler the comparator works on Entry<Long, Long>, so the type witness disappears from the pipeline. It's still needed inside the method, but nobody reading the pipeline has to look at it. The method name also records the tie-break rule. The collector is generic for free, because nothing in it depends on Long.

Looking at the cleaned-up pipeline, I noticed something.

The observation: this isn't one stream, it's two

collect is a terminal operation. It ends the first stream. .entrySet().stream() then starts a second one. What looks like a single fluent pipeline is actually two pipelines joined by a Map.

My first explanation was "inside a stream operation, a lambda can only see the element it's given, not the others." That's close, but not quite the full story. Stateful intermediate operations do exist: sorted() and distinct() both see every element before passing anything on. The real constraints are these:

  1. Frequency is a global property. You can't know how often any element occurs until you've read the whole input. Something has to collect everything before the next step can start.
  2. Before Java 24 you couldn't write your own stateful intermediate operation. The built-in operations like sorted and distinct were the only ones. Your own lambdas in map and filter are expected to be stateless and to work on one element at a time, as the stream non-interference rules require. You can cheat by capturing an outside HashMap in a lambda, but that's fragile and breaks under parallel streams.

So the only legal way to build a frequency map in the middle of a pipeline was a terminal collect, followed by a new stream over its result.

Step 3: One stream with a Gatherer

Java 24 finalised Stream Gatherers (JEP 485), and Java 25 is the first LTS that includes them. Stream.gather(...) lets you write your own intermediate operation, which is exactly the missing piece. Here is the single-stream version:

import java.math.BigInteger; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.stream.Gatherer; public class TopIdProduct { public static BigInteger productOfTop3(List<Long> ids) { return ids.stream() .gather(countingFrequency()) .sorted(byFrequencyDescThenIdAsc()) .limit(3) .map(e -> BigInteger.valueOf(e.getKey())) .reduce(BigInteger.ONE, BigInteger::multiply); } private static <T> Gatherer<T, ?, Entry<T, Long>> countingFrequency() { return Gatherer.<T, Map<T, Long>, Entry<T, Long>>ofSequential( HashMap::new, Gatherer.Integrator.ofGreedy((freq, element, downstream) -> { freq.merge(element, 1L, Long::sum); return true; }), (freq, downstream) -> { for (Entry<T, Long> e : freq.entrySet()) { if (!downstream.push(Map.entry(e.getKey(), e.getValue()))) { break; } } }); } private static Comparator<Entry<Long, Long>> byFrequencyDescThenIdAsc() { return Entry.<Long, Long>comparingByValue(Comparator.reverseOrder()) .thenComparing(Entry.comparingByKey()); } public static void main(String[] args) { List<Long> ids = List.of(7L, 3L, 7L, 5L, 3L, 7L, 9L, 5L, 3L, 2L); System.out.println(productOfTop3(ids)); // 105 } } 

▶ Try it on JBang

The Gatherer has three parts:

  • An initializer (HashMap::new) creates the state, which here is the frequency map.
  • The integrator reads each element and only updates the counts. It sends nothing downstream yet. It's greedy because it never stops reading the input early.
  • The finisher runs after the input is used up and pushes the finished counts downstream. It stops early if a later step (like limit) needs no more elements. Map.entry(...) makes an unchangeable copy instead of handing out the HashMap's live entry objects.

The call site is lovely: one stream that reads exactly like the problem statement.

Why I didn't keep it

The helper is a different story. Compare it with the collector it replaces:

Collectors.groupingBy(Function.identity(), Collectors.counting()) 

The Gatherer has a three-part generic signature, an integrator factory, a lambda with three parameters, and an early-exit loop. It's correct and reusable, but it's library code. For a one-off task, it's far more machinery than the problem deserves.

It also doesn't make the code any faster. Like sorted(), the Gatherer has to read the whole input before it emits anything. "One stream" is a difference in how the code reads, not in how it runs. The two-stream version isn't a workaround; the barrier is there either way.

Step 4: The clean hybrid

So I went back to the two-stream version and cleaned it up. Two more extractions gave the top-level method the shape I wanted: frequencies(ids) and a top-n method with n as a parameter.

My first attempt was mostFrequent(frequencies(ids), 3). It works, but nested calls read inside-out, and I didn't like it. Java has no extension methods, and Stream has no transform or let method (String.transform exists, Stream.transform doesn't). So a step you write yourself can never be chained as .mostFrequent(3). It's always either a nested call or an argument to a built-in operation.

The way out is to let each method call the next one internally instead of composing them at the top level. frequencies returns a stream of (id, count) entries, and mostFrequent takes the raw IDs:

import static java.util.function.Function.identity; import static java.util.stream.Collectors.counting; import static java.util.stream.Collectors.groupingBy; import java.math.BigInteger; import java.util.Collection; import java.util.Comparator; import java.util.List; import java.util.Map.Entry; import java.util.stream.Stream; public class TopIdProduct { public static BigInteger productOfTop3(List<Long> ids) { return mostFrequent(ids, 3) .map(BigInteger::valueOf) .reduce(BigInteger.ONE, BigInteger::multiply); } private static Stream<Long> mostFrequent(Collection<Long> ids, int n) { return frequencies(ids) .sorted(byFrequencyDescThenIdAsc()) .limit(n) .map(Entry::getKey); } private static <T> Stream<Entry<T, Long>> frequencies(Collection<T> items) { return items.stream() .collect(groupingBy(identity(), counting())) .entrySet().stream(); } private static Comparator<Entry<Long, Long>> byFrequencyDescThenIdAsc() { return Entry.<Long, Long>comparingByValue(Comparator.reverseOrder()) .thenComparing(Entry.comparingByKey()); } public static void main(String[] args) { List<Long> ids = List.of(7L, 3L, 7L, 5L, 3L, 7L, 9L, 5L, 3L, 2L); System.out.println(productOfTop3(ids)); // 105 } } 

Source:https://dev.to/verhasi/two-streams-one-gatherer-and-a-clean-hybrid-multiplying-the-most-frequent-ids-in-java-3l10