Java Collectors: joining, toMap, groupingBy, partitioningBy and teeing (OCP 21)
The Collectors class for the OCP 21 exam: joining, averaging, summing, counting, toCollection, toList versus Stream.toList, toMap with merge functions and duplicate keys, groupingBy, partitioningBy, mapping, filtering, teeing, plus Spliterator and how a stream sees later changes to its source.
kvi5hnuCode Sprout team member10 min readOn this page
collect(Collector) is the terminal operation that turns a stream into almost anything: a String, a number, a Set, a Map of lists. You rarely write a Collector yourself. The Collectors class (plural, like Collections and Arrays) has static factory methods for all the common ones. A Collector does nothing on its own. It only runs when you hand it to collect.
This article also covers two leftovers from the "advanced pipeline" part of the objectives: when a stream reads its source, and Spliterator.
A stream reads its source late
A stream doesn't copy its source when you create it. It's a recipe that reads the data when the terminal operation runs:
var trees = new ArrayList<String>(List.of("oak", "elm"));
Stream<String> s = trees.stream(); // nothing read yet
trees.add("ash"); // changed before the terminal operation
System.out.println(s.count()); // 3
On the exam, count elements at the moment the terminal operation runs, not when stream() was called. Changing the source during the terminal operation is a different matter. For an ArrayList it usually ends in a ConcurrentModificationException, so don't do it.
Basic collectors
All of these are static methods on Collectors. The exam often static-imports them, so you'll see groupingBy(...) with no class name.
| Collector | Result of collect | Notes |
|---|---|---|
joining(), joining(delim), joining(delim, prefix, suffix) | String | elements must be CharSequences |
counting() | Long | |
averagingInt/Long/Double(f) | Double | 0.0 for an empty stream |
summingInt(f), summingLong(f), summingDouble(f) | Integer, Long, Double | matches the primitive type |
summarizingInt/Long/Double(f) | IntSummaryStatistics etc. | count, sum, min, max, average |
minBy(cmp), maxBy(cmp) | Optional<T> | empty for an empty stream |
toList(), toSet() | List<T>, Set<T> | no guarantee of type or mutability |
toUnmodifiableList(), toUnmodifiableSet(), toUnmodifiableMap(...) | unmodifiable | Java 10+, reject null elements |
toCollection(supplier) | any Collection you choose | e.g. toCollection(TreeSet::new) |
String csv = Stream.of("red", "green").collect(Collectors.joining(", ", "[", "]")); // [red, green]
Double avg = Stream.of("ab", "abc").collect(Collectors.averagingInt(String::length)); // 2.5
Integer sum = Stream.of("ab", "abc").collect(Collectors.summingInt(String::length)); // 5
Long n = Stream.of("ab", "abc").collect(Collectors.counting()); // 2
TreeSet<String> sorted = Stream.of("b", "c", "a").collect(Collectors.toCollection(TreeSet::new));
Return-type traps (all checked with javac):
int n = stream.collect(counting());doesn't compile, becauseLongcan't unbox to anint. UselongorLong.Integer avg = stream.collect(averagingInt(...));doesn't compile. Averages are alwaysDouble, thoughdoubleworks through unboxing.Stream<Integer>can't usejoining()directly. Map toStringfirst, for example withmap(String::valueOf).Collector.toList()(singular) doesn't exist. Factories are onCollectors.
Collectors.toList() versus Stream.toList()
collect(Collectors.toList()) | stream.toList() (Java 16+) | |
|---|---|---|
| Can you modify the result? | in practice yes (currently an ArrayList), but the Javadoc promises nothing | no: add throws UnsupportedOperationException |
null elements | allowed | allowed |
| Exam view | the "mutable" list | the unmodifiable shortcut |
If you really need a mutable list, say so: collect(Collectors.toCollection(ArrayList::new)). Collectors.toUnmodifiableList() is also unmodifiable, but unlike Stream.toList() it throws a NullPointerException on a null element.
Collecting into a map with toMap
toMap needs two functions: one for the key and one for the value.
Map<String, Integer> lengths = Stream.of("lion", "owl")
.collect(Collectors.toMap(s -> s, String::length)); // {owl=3, lion=4}
s -> s can also be written Function.identity().
Duplicate keys throw. If two elements produce the same key and you didn't say how to combine them, the collector throws an IllegalStateException:
Stream.of("lion", "bear").collect(Collectors.toMap(String::length, s -> s));
// IllegalStateException: Duplicate key 4 (attempted merging values lion and bear)
The three- and four-argument versions fix that and choose the map type:
| Form | Adds |
|---|---|
toMap(keyFn, valueFn) | nothing: duplicates throw, and the map type isn't specified (currently HashMap) |
toMap(keyFn, valueFn, mergeFn) | a BinaryOperator that combines two values for the same key |
toMap(keyFn, valueFn, mergeFn, mapSupplier) | the map implementation, e.g. TreeMap::new |
TreeMap<Integer, String> byLength = Stream.of("lion", "bear", "owl")
.collect(Collectors.toMap(String::length, s -> s, (a, b) -> a + "," + b, TreeMap::new));
// {3=owl, 4=lion,bear}
There's no toMap(keyFn, valueFn, mapSupplier). To choose the map type you must also pass a merge function. A value function that returns null causes a NullPointerException, because toMap doesn't allow null values.
Grouping with groupingBy
![Top: groupingBy with String::length as the classifier sends fig, kiwi, plum, lime and apple into buckets for keys 3, 4 and 5; the downstream collector turns each bucket into a map value, giving 3=[fig], 4=[kiwi, plum, lime], 5=[apple] with toList or 3=1, 4=3, 5=1 with counting. Bottom: partitioningBy with a predicate always produces exactly the two keys false and true, even when one list is empty](https://code-sprout-content.laxmi.solutions/asset/2026/11/3qzwidcjd5ha5c4t.png)
groupingBy takes a classifier function. Every element whose classifier returns the same key goes into the same bucket:
Map<Integer, List<String>> byLen = Stream.of("fig", "kiwi", "plum", "apple")
.collect(Collectors.groupingBy(String::length));
// {3=[fig], 4=[kiwi, plum], 5=[apple]}
There are three versions:
| Form | Map type | Value type |
|---|---|---|
groupingBy(classifier) | unspecified (currently HashMap) | List<T> |
groupingBy(classifier, downstream) | unspecified | whatever the downstream collector returns |
groupingBy(classifier, mapFactory, downstream) | the one you supply | whatever the downstream collector returns |
There's no groupingBy(classifier, mapFactory). To pick the map type you also need a downstream collector, even if it's just toList():
TreeMap<Integer, List<String>> t = words.collect(
Collectors.groupingBy(String::length, TreeMap::new, Collectors.toList()));
The downstream collector decides what each bucket becomes. Any collector works:
Map<Integer, Long> counts = words.collect(groupingBy(String::length, counting()));
Map<Integer, Set<String>> sets = words.collect(groupingBy(String::length, toSet()));
Map<Integer, Double> avgs = words.collect(groupingBy(String::length, averagingInt(String::length)));
Map<Integer, Optional<String>> lastAlpha = words.collect(groupingBy(String::length, maxBy(Comparator.<String>naturalOrder())));
Declared types must match exactly. Map<Integer, Integer> m = …groupingBy(String::length, counting()) doesn't compile, because the values are Long. Plain groupingBy(String::length) can't be assigned to Map<Integer, Set<String>>, because the values are Lists.
The classifier must not return null. A null key throws NullPointerException: element cannot be mapped to a null key.
mapping, filtering and flatMapping
These are adapters used as downstream collectors. They change elements inside each bucket before passing them to another collector:
| Adapter | Since | Does |
|---|---|---|
mapping(fn, downstream) | 8 | transforms each element, then collects |
filtering(pred, downstream) | 9 | keeps matching elements, then collects |
flatMapping(fn, downstream) | 9 | expands each element into a stream, then collects |
Map<Integer, List<Character>> initials = words.collect(
groupingBy(String::length, mapping(s -> s.charAt(0), toList())));
Map<Integer, Optional<Character>> lastLetter = words.collect(
groupingBy(String::length, mapping(s -> s.charAt(s.length() - 1), maxBy((a, b) -> a - b))));
This "grouping, then mapping, then max" chain is the most deeply nested collector the exam expects you to read. Read it from the outside in:
- Group by length.
- Inside each group, turn each word into its last character.
- Keep the largest character, wrapped in an
Optional.
filtering differs from calling filter before grouping. filter first removes elements, so a group whose elements are all removed disappears from the map. filtering keeps the key and gives it an empty collection. The example program below shows tea=[].
Partitioning with partitioningBy
Partitioning is grouping with a Predicate, so there are only two keys, false and true:
Map<Boolean, List<String>> longWords = Stream.of("fig", "kiwi", "apple")
.collect(Collectors.partitioningBy(s -> s.length() > 4));
// {false=[fig, kiwi], true=[apple]}
Map<Boolean, Long> veryLong = Stream.of("fig", "kiwi")
.collect(Collectors.partitioningBy(s -> s.length() > 9, Collectors.counting()));
// {false=2, true=0}
groupingBy | partitioningBy | |
|---|---|---|
| Classifier | Function (any key type) | Predicate (key is Boolean) |
| Keys present | only keys that occurred; an empty stream gives {} | always both false and true, even for an empty stream |
| Downstream collector | optional | optional |
| Map-type supplier | optional (with downstream) | not available |
groupingBy(s -> s.length() > 4) does compile and gives a Map<Boolean, List<String>>. But a key that never occurs is missing, while partitioningBy would show it with an empty list. partitioningBy(String::length) doesn't compile, because the argument must return a boolean.
Two results in one pass: teeing
A stream can be consumed only once. Collectors.teeing (Java 12) sends every element to two collectors and then combines their results with a BiFunction:
record Range(Optional<Integer> low, Optional<Integer> high) {}
Range r = Stream.of(7, 2, 9).collect(Collectors.teeing(
Collectors.minBy(Comparator.naturalOrder()),
Collectors.maxBy(Comparator.naturalOrder()),
Range::new));
// Range[low=Optional[2], high=Optional[9]]
That's three collectors in total: the two inner ones plus teeing itself. All three arguments are required.
Splitting work with Spliterator
A Spliterator ("splittable iterator") is what streams use internally to divide data, for example for parallel processing. You get one from collection.spliterator() or stream.spliterator(). You only need to use one for the exam, not write one:
| Method | Does |
|---|---|
Spliterator<T> trySplit() | removes roughly the first half of the remaining elements and returns them as a new Spliterator. Returns null when it can't split further. |
boolean tryAdvance(Consumer<? super T>) | processes one element, if there is one. Returns whether it did. |
void forEachRemaining(Consumer<? super T>) | processes all remaining elements |
Spliterator<String> all = List.of("a1", "a2", "a3", "a4", "a5", "a6", "a7").spliterator();
Spliterator<String> front = all.trySplit();
front.forEachRemaining(System.out::print); // a1a2a3
all.tryAdvance(System.out::print); // a4
all.forEachRemaining(System.out::print); // a5a6a7
System.out.println(all.tryAdvance(x -> {})); // false
After the split, the original spliterator keeps only what wasn't handed off. An infinite stream's spliterator can still split. It hands out a chunk of elements rather than "half of infinity". Using tryAdvance on it is fine, but forEachRemaining would never end. Spliterators also report characteristics such as SIZED, ORDERED and SORTED; an infinite stream is not SIZED.
What's current
- Nothing in this article changed in Java 22 through 25, so the rules apply to both the Java 21 exam (1Z0-830) and the Java 25 exam (1Z0-831).
Collectors.teeing(Java 12) is the newest collector in this article.Collectors.toUnmodifiableList,toUnmodifiableSetandtoUnmodifiableMap(Java 10) are current too.
Exam traps from this article
A complete example
A small café order log shows every collector from this article. It counts orders after the source list changes, then joins, averages, sums and builds a TreeSet. It shows a toMap duplicate-key failure and fixes it with a merge function and TreeMap::new. It groups by category with counting, mapping and maxBy, compares filtering with empty groups, partitions by price, combines two totals with teeing, and finally splits the orders with a Spliterator.
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Spliterator;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Solution {
record Order(String item, String category, double price, int qty) {}
record Receipt(long orders, double revenue) {}
public static void main(String[] args) {
var orders = new ArrayList<Order>(List.of(
new Order("latte", "coffee", 4.20, 2),
new Order("scone", "bakery", 3.10, 1),
new Order("mocha", "coffee", 4.80, 1),
new Order("bagel", "bakery", 2.90, 3),
new Order("chai", "tea", 3.60, 2)));
// The stream reads its source only when the terminal operation runs
Stream<Order> pending = orders.stream();
orders.add(new Order("espresso", "coffee", 2.50, 4));
System.out.println("orders seen: " + pending.count());
// Basic collectors
String menu = orders.stream().map(Order::item)
.collect(Collectors.joining(", ", "[", "]"));
Double avgPrice = orders.stream().collect(Collectors.averagingDouble(Order::price));
Integer cups = orders.stream().collect(Collectors.summingInt(Order::qty));
TreeSet<String> categories = orders.stream().map(Order::category)
.collect(Collectors.toCollection(TreeSet::new));
System.out.printf("menu %s%navg price %.2f, items sold %d, categories %s%n",
menu, avgPrice, cups, categories);
// toMap: duplicate keys need a merge function
try {
orders.stream().collect(Collectors.toMap(Order::category, Order::item));
} catch (IllegalStateException e) {
System.out.println("toMap failed: " + e.getMessage());
}
TreeMap<String, String> byCategory = orders.stream().collect(Collectors.toMap(
Order::category, Order::item, (a, b) -> a + "+" + b, TreeMap::new));
System.out.println("toMap merged: " + byCategory);
// groupingBy with downstream collectors
Map<String, Long> counts = orders.stream()
.collect(Collectors.groupingBy(Order::category, TreeMap::new, Collectors.counting()));
Map<String, List<String>> names = orders.stream()
.collect(Collectors.groupingBy(Order::category, TreeMap::new,
Collectors.mapping(Order::item, Collectors.toList())));
Map<String, Optional<Order>> priciest = orders.stream()
.collect(Collectors.groupingBy(Order::category, TreeMap::new,
Collectors.maxBy(Comparator.comparingDouble(Order::price))));
System.out.println("counts: " + counts);
System.out.println("names: " + names);
priciest.forEach((cat, o) -> System.out.println(" top " + cat + ": " + o.map(Order::item).orElse("-")));
// filtering keeps every group; filter() first would drop the empty ones
Map<String, List<String>> bulk = orders.stream()
.collect(Collectors.groupingBy(Order::category, TreeMap::new,
Collectors.filtering(o -> o.qty() >= 3,
Collectors.mapping(Order::item, Collectors.toList()))));
System.out.println("bulk (filtering): " + bulk);
// partitioningBy always has both keys
Map<Boolean, List<String>> premium = orders.stream()
.collect(Collectors.partitioningBy(o -> o.price() >= 4.0,
Collectors.mapping(Order::item, Collectors.toList())));
Map<Boolean, Long> huge = orders.stream()
.collect(Collectors.partitioningBy(o -> o.qty() > 10, Collectors.counting()));
System.out.println("premium: " + premium + ", huge: " + huge);
// teeing: two collectors, one pass, one combined result
Receipt receipt = orders.stream().collect(Collectors.teeing(
Collectors.counting(),
Collectors.summingDouble(o -> o.price() * o.qty()),
Receipt::new));
System.out.printf("receipt: %d orders, revenue %.2f%n", receipt.orders(), receipt.revenue());
// Spliterator: split the work into pieces
Spliterator<Order> all = orders.spliterator();
Spliterator<Order> firstHalf = all.trySplit();
System.out.print("first half: ");
firstHalf.forEachRemaining(o -> System.out.print(o.item() + " "));
System.out.print("| one more: ");
all.tryAdvance(o -> System.out.print(o.item() + " "));
System.out.print("| rest: ");
all.forEachRemaining(o -> System.out.print(o.item() + " "));
System.out.println("| anything left? " + all.tryAdvance(o -> {}));
}
}
Output:
orders seen: 6
menu [latte, scone, mocha, bagel, chai, espresso]
avg price 3.52, items sold 13, categories [bakery, coffee, tea]
toMap failed: Duplicate key coffee (attempted merging values latte and mocha)
toMap merged: {bakery=scone+bagel, coffee=latte+mocha+espresso, tea=chai}
counts: {bakery=2, coffee=3, tea=1}
names: {bakery=[scone, bagel], coffee=[latte, mocha, espresso], tea=[chai]}
top bakery: scone
top coffee: mocha
top tea: chai
bulk (filtering): {bakery=[bagel], coffee=[espresso], tea=[]}
premium: {false=[scone, bagel, chai, espresso], true=[latte, mocha]}, huge: {false=6, true=0}
receipt: 6 orders, revenue 42.20
first half: latte scone mocha | one more: bagel | rest: chai espresso | anything left? false
Points to notice:
pending.count()saw 6 orders. The espresso was added afterstream()but beforecount().- The first
toMapfailed on the secondcoffeekey. The merge function(a, b) -> a + "+" + bcombined all three coffee items. filteringkepttea=[]in the map. Callingfilter(o -> o.qty() >= 3)beforegroupingBywould have removed theteakey entirely.- The
hugepartition had no matches, but still printedtrue=0. teeingbuilt aReceiptfromcounting()andsummingDouble(...)in a single pass.Receipt::newwas the combiningBiFunction.- The
Spliteratorof six orders split three to the front;tryAdvancethen took one, andforEachRemainingemptied the rest.
Common questions
Is the map from groupingBy or toMap a HashMap?
Currently yes, but the API doesn't promise it. If order matters, pass TreeMap::new or LinkedHashMap::new with the forms that accept a supplier.
When should I use groupingByConcurrent or toConcurrentMap?
They're for parallel streams, covered in the concurrency chapter. On sequential streams, use the normal versions.
What about Collectors.reducing?
It's a general-purpose reduction collector. It isn't on the exam; reduce on the stream or the specific collectors cover the same needs.
Is collectingAndThen on the exam?
It isn't a core objective, but it's handy: collectingAndThen(toList(), List::size) runs a final function on the collected result.
Summary
collect(Collectors.x(...))turns a stream into a result. The basic collectors arejoining,counting,averagingX,summingX,summarizingX,minBy/maxBy,toList,toSetandtoCollection.toMap(key, value[, merge[, mapSupplier]])throwsIllegalStateExceptionon duplicate keys unless you give a merge function.groupingBy(classifier[, mapFactory], downstream)builds aMap<K, List<T>>by default, or whatever the downstream collector produces.mapping,filteringandflatMappingadapt elements inside each group.partitioningBy(predicate[, downstream])always has thefalseandtruekeys.teeing(c1, c2, combiner)merges two collectors' results in one pass.- A stream reads its source when the terminal operation runs. A
Spliteratorsplits data withtrySplitand processes it withtryAdvanceandforEachRemaining.
Practice quiz
Test yourself with the collectors quiz: 10 exam-style questions with explanations.
You've finished Chapter 10. Check your understanding of the whole chapter with the Chapter 10 review quiz: 20 mixed questions on Optional, stream pipelines, terminal and intermediate operations, primitive streams, and collectors.
Previous: Java Primitive Streams: IntStream, LongStream, DoubleStream and Summary Statistics (OCP 21)
Next: Java Exceptions: Checked vs Unchecked, the Throwable Hierarchy and Overriding Rules (OCP 21)
Related reading
- Java Primitive Streams: IntStream, LongStream, DoubleStream and Summary Statistics (OCP 21)
- Java Stream Intermediate Operations: filter, map, flatMap, sorted, distinct, limit and peek (OCP 21)
- Java Stream Terminal Operations: count, min, max, find, match, forEach, reduce and collect (OCP 21)
- Java Streams: Pipeline Flow and Creating Finite and Infinite Streams (OCP 21)
- Java Optional: Creating, Checking and Unwrapping Optional Values (OCP 21)

More in OCP Java 21
OCP Java 21 Mock Exam 3 (1Z0-830)
The third full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), weighted toward the hardest areas: streams, concurrency, generics, modules and I/O. 120 minutes, 68% to pass, with explanations.
OCP Java 21 Mock Exam 2 (1Z0-830)
The second full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830): new questions on every objective, with more multi-select. 120 minutes, 68% to pass, with an explanation for every answer.
OCP Java 21 Mock Exam 1 (1Z0-830)
A full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), covering every objective at exam difficulty. 120 minutes, 68% to pass, with an explanation for every answer.
Quiz: Final Review (OCP 21)
Ten exam-style questions mixing the most-tested OCP Java 21 rules from the final checklist: promotion, String immutability, overloading, initialization order, collections, streams, exceptions and switch patterns, with explanations.
Discussion
Sign in to ask a question or share what you learned.