Skip to the page

Types, errors and modern syntax · mid

Streams and collectors, and when not to go parallel

Streams group, filter and aggregate data in memory. Collectors.toMap fails on duplicate keys. A parallel stream uses a shared pool and is rarely right in a web handler.

The notes

What you must know

  • Top per group: toMap(keyFn, e -> e, BinaryOperator.maxBy(comparator)). Average per group: groupingBy(keyFn, averagingLong(...)). Pass TreeMap::new for sorted keys.
  • Second highest: map(...).distinct().sorted(reverseOrder()).skip(1).findFirst().
  • maxBy keeps one element on ties. If all tied elements are needed, group into lists and filter by the maximum.
  • Collectors.toMap throws IllegalStateException ("Duplicate key") when two elements map to the same key. The message names the key and both values. It also throws NullPointerException for a null value.
  • A real key is the business key. Keeping the first duplicate silently drops data. Use groupingBy into lists, or a merge function only when the business rule allows it.
  • Stream.toList() (Java 16) returns an unmodifiable list. The default toMap map has no order: use the four-argument form for LinkedHashMap or TreeMap.
  • Money: averaging returns a double. Keep paise as long or use BigDecimal and round on purpose.
  • Parallel streams run on the shared common ForkJoinPool (CPU count minus one threads) plus the calling thread. Blocking calls inside tie up the whole JVM. Adding to a shared ArrayList from forEach is a race. Use collect. Prove speed with JMH and a load test.

The red pen

Common traps: mistake → fix

  • Mistake: toMap is safe when keys look unique

    Fix: data changes, and a duplicate throws at 2 am.

  • Mistake: parallelStream always makes it faster

    Fix: small lists, blocking calls and busy servers get slower.

  • Mistake: Streams are better than SQL for big data

    Fix: aggregate large data in the database.

Easy to hard

Questions interviewers ask, easy to hard

  1. Give the highest-paid employee per department with streams.
  2. What does IllegalStateException: Duplicate key mean, and how do you fix it properly?
  3. Would you approve parallelStream in an API handler? Why?
  4. How do you get the second highest salary?

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview