Command Palette

Search for a command to run...

Back to the lesson: Topic 10.6 — Collectors
Core Java · Example 4 of 5 Java 16+

partitioningBy, collectingAndThen and teeing

Collectors.teeing arrived in Java 12. It reads the data once and feeds both collectors.

A collector is a recipe that tells stream.collect(...) how to build a result: a list, a set, a joined string, a map, or a map of groups with counts and totals. Collectors provides ready-made ones like toMap, groupingBy, partitioningBy, joining and teeing, and they can be nested to answer questions like "total sales per city" in one pipeline.

Change the code and press Run (Ctrl+Enter). Try to predict the output first, then break it on purpose and read the error. Your edits are saved and match the lesson page.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Given words "apple", "bat", "cherry", "dog", "egg", group them by length into a TreeMap and print it.

02

Count how many times each character appears in "banana" and print the result as a TreeMap<Character, Long>.

03

From a list of (name, dept, salary) employees, print the highest-paid employee's name per department, using groupingBy with collectingAndThen and maxBy.

Explain it without notes

01

What are the components of a Collector, and what does each do?

02

How does toMap behave with duplicate keys and null values, and how do you control it?

03

Explain groupingBy with a downstream collector, using an example.

04

What is the difference between filtering before groupingBy and using Collectors.filtering as a downstream?

05

When would you use partitioningBy, collectingAndThen and teeing?

partitioningBy, collectingAndThen and teeing Java 16+
Sign in to run this example in your browser.

Expected output

passed: [Asha, Meera], failed: [Ravi, Kabir]
empty input still has both keys: {false=0, true=0}
topper: Asha
lowest 28, highest 92
average: 55.5