Skip to content
Tutorials Center
My learning

Topics

Lesson 102 of 201 ยท Generics and Functional Programming

Collecting Stream Results

Learn Java stream collectors - toList, toSet, toMap with merge functions, groupingBy with downstream collectors, partitioningBy, joining, summarizing and reduce.

A stream pipeline ends with a terminal operation, and the most flexible one is collect. You hand it a collector, a recipe for building a result from the elements, and it can produce almost anything: a list, a set, a map from keys to values, a joined string, statistics, or a map of groups where each group is itself summarized. Most collectors come ready-made from the java.util.stream.Collectors class.

If you've written "count how many orders each customer placed" with a HashMap and a loop, you'll like this lesson: that whole loop becomes one groupingBy call. You'll learn the simple collectors, toMap and its duplicate-key trap, groupingBy with downstream collectors, partitioningBy, joining, summarizing collectors and reduce. This lesson assumes you know the basics from Streams.

collect, toList and the basic collectors

collect(collector) is a terminal operation. The simplest collectors build collections:

Collector Result
Collectors.toList() A List (in practice an ArrayList, but that isn't guaranteed)
Collectors.toUnmodifiableList() An unmodifiable List
Collectors.toSet() A Set without duplicates (no guaranteed order)
Collectors.toCollection(TreeSet::new) Any collection you choose
Collectors.joining(", ", "[", "]") One String with a separator, prefix and suffix
Collectors.counting() The number of elements, as a Long

Since Java 16 there's also the shortcut stream.toList(), which returns an unmodifiable list. Prefer it when you just need a list; reach for collect when you need something else.

Java Basic collectors: lists, sets, any collection and joining

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

joining works only on CharSequence elements (like String), so map other types to strings first. For numbers: .map(String::valueOf).collect(Collectors.joining("+")).

Many lessons import collectors statically: import static java.util.stream.Collectors.*;. Then you can write collect(groupingBy(..., counting())), which reads much better when collectors are nested. The examples below use the explicit Collectors. prefix so you can see where each method lives.

toMap: building maps, and the duplicate-key trap

Collectors.toMap(keyMapper, valueMapper) turns each element into one map entry. It works well when keys are unique, such as an ID:

Java
Map<String, Employee> byId = employees.stream()
    .collect(Collectors.toMap(Employee::id, e -> e));   // or Function.identity()

If two elements produce the same key, the two-argument toMap throws IllegalStateException: Duplicate key .... When duplicates are possible, pass a third argument, a merge function that decides what to keep. A fourth argument chooses the map type, for example TreeMap::new for sorted keys or LinkedHashMap::new to keep encounter order.

Java toMap with a merge function and a chosen map type

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The first attempt fails as soon as the second "tea" arrives. With Integer::sum as the merge function, colliding values are added, which is often exactly what you want. Note that toMap also throws a NullPointerException if a value mapper returns null.

groupingBy: the most useful collector

Collectors.groupingBy(classifier) sorts elements into buckets. The classifier function computes a key for each element, and the result is a Map<Key, List<Element>>:

Java
Map<String, List<Sale>> byCity = sales.stream()
    .collect(Collectors.groupingBy(Sale::city));
// {Lisbon=[Sale[...tea...], Sale[...cocoa...], Sale[...coffee...]], Porto=[...]}

The real power comes from the optional second argument, a downstream collector that decides what to do with each group instead of putting it in a list. Here are the ones you'll use most:

Downstream collector Each group becomes
counting() The number of elements (Long)
summingInt(f) / summingDouble(f) The sum of a property
averagingInt(f) / averagingDouble(f) The average of a property (Double)
mapping(f, downstream) Elements transformed first, then collected by downstream
filtering(p, downstream) (Java 9) Only matching elements, then collected (empty groups still appear)
flatMapping(f, downstream) (Java 9) Each element expanded into a stream, then collected
maxBy(comparator) / minBy(comparator) An Optional with the largest/smallest element
toSet(), joining(...), toList() A set, a string or a list
collectingAndThen(downstream, finisher) The downstream result, transformed once more

A three-argument form, groupingBy(classifier, mapFactory, downstream), picks the map type, for example TreeMap::new to get groups sorted by key.

Java groupingBy with downstream collectors

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Read nested collectors from the outside in: "group by department, and for each department, map employees to their names and collect a list." maxBy returns an Optional because, in general, a collector can't know the group isn't empty; inside groupingBy it never is, so orElseThrow() is safe there.

The plain groupingBy returns a HashMap, so keys come out in no particular order. Whenever you print a grouped result or show it to users, pass TreeMap::new (sorted) or LinkedHashMap::new (first-seen order). The examples here do that so their output is stable.

partitioningBy: exactly two groups

Collectors.partitioningBy(predicate) is a special grouping with a boolean key. The result always has both keys, false and true, even if one of the lists is empty. That makes it a better fit than groupingBy for yes/no splits like passed/failed or in stock/sold out. It also accepts a downstream collector.

Java partitioningBy for pass/fail splits

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Summaries, statistics and teeing

To compute several numbers in one pass, use a summarizing collector: summarizingInt, summarizingLong or summarizingDouble. It returns a statistics object with getCount, getSum, getMin, getMax and getAverage. These also work as downstream collectors, giving you full statistics per group.

Collectors.teeing(c1, c2, merger) (Java 12) sends every element to two collectors and combines their results, for example to get the cheapest and most expensive item at once, or a count and a total.

Java summarizingInt per group and teeing

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

reduce: combining elements into one value

reduce is a terminal operation (not a collector) that folds all elements into a single result by applying a combining function over and over. It comes in three forms:

Java
// 1. With an identity: never empty, returns T
int total = numbers.stream().reduce(0, Integer::sum);

// 2. Without an identity: may be empty, returns Optional<T>
Optional<Integer> product = numbers.stream().reduce((a, b) -> a * b);

// 3. With a different result type: identity, accumulator, combiner
int totalLength = words.stream().reduce(0, (sum, w) -> sum + w.length(), Integer::sum);

The identity must be a neutral value for the operation: 0 for addition, 1 for multiplication, "" for concatenation. The function must be associative ((a + b) + c equals a + (b + c)), because parallel streams split the work and combine partial results in any grouping. Subtraction isn't associative, so reduce(0, (a, b) -> a - b) is a bug waiting to happen.

Java reduce in its three forms

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

In practice, prefer the specialized operations when they exist (sum(), max(), count(), joining), because they say what you mean. Use reduce for custom combinations such as merging records or composing functions. Never use reduce to build up a mutable collection like a list; that's what collect is for.

Choosing the right tool

  • One list: stream.toList().
  • A set or a specific collection: Collectors.toSet() or toCollection(...).
  • A lookup by unique key: toMap(key, value); add a merge function if keys might repeat.
  • Buckets by a property: groupingBy, with a downstream collector for counts, sums or names.
  • A yes/no split: partitioningBy.
  • A single string: joining.
  • Several numbers at once: summarizingInt/Double, or teeing.
  • One combined value: a specialized method, otherwise reduce.

For collector tricks such as flatMapping, mapMulti and the newer stream gatherers, continue to Advanced Streams.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What happens with Stream.of("ab", "cd", "ab").collect(Collectors.toMap(s -> s, String::length))?

    The two-argument toMap fails on duplicate keys. Pass a merge function as the third argument to decide how colliding values combine.
  2. 2. What type does people.stream().collect(Collectors.groupingBy(Person::city, Collectors.counting())) return?

    counting() produces a Long per group, so the result maps each city to a Long.
  3. 3. List.of(5, 15, 25).stream().collect(Collectors.partitioningBy(n -> n > 100)) returns which map?

    partitioningBy always contains both the false and the true key, even when one list is empty.
  4. 4. Why is reduce(0, (a, b) -> a - b) a bad idea?

    reduce requires an associative function and a true identity value. Subtraction breaks associativity, so parallel execution can give wrong answers.
  5. 5. What does Stream.of("b", "a").sorted().collect(Collectors.joining("-", "<", ">")) return?

    The separator goes between elements, and the prefix and suffix wrap the whole result once.

Summary

  • collect(collector) builds a result from stream elements; Collectors provides ready-made collectors, and stream.toList() is the shortcut for an unmodifiable list.
  • toMap(key, value) throws on duplicate keys; add a merge function (Integer::sum, keep-first, keep-max) and optionally a map factory like TreeMap::new.
  • groupingBy(classifier) makes a Map<K, List<T>>; a downstream collector (counting, summingInt, averagingDouble, mapping, maxBy, collectingAndThen, another groupingBy) summarizes each group.
  • partitioningBy(predicate) always returns both true and false keys.
  • joining, summarizingInt/Double and teeing produce strings, statistics and combined results in one pass.
  • reduce folds elements into one value; its identity must be neutral and its function associative. Prefer specialized operations when they exist.

Next: Advanced Streams, covering flatMap, mapMulti, takeWhile, infinite streams, parallel streams and Java 24 gatherers.