Counting, Collecting and Flattening Streams
Count, total, join, group and flatten a list of objects with streams, and read any stream as intermediate steps followed by one terminal step.
Journeyman · Java · Updated
After this lesson you can
- Summarize a stream with count, and with mapToInt or mapToDouble and sum, average, min and max
- Collect a stream with Collectors.joining and groupingBy, and flatten a list of lists with flatMap
Key takeaways
- count gives a long, and mapToInt or mapToDouble turn a stream into plain numbers that have sum, average, min and max.
- average, min and max give back a box that might be empty, because an empty list has no answer. orElse says what to use then.
- collect builds the result with a collector. Collectors.joining makes one String, and groupingBy makes a Map with a group for each key.
- flatMap turns a stream of lists into one stream of their items.
- Intermediate operations give back a stream. One terminal operation ends it, and a stream can be used only once.
Back at the online grocery store, the products are sorted, paged and checked. Now the requests are about numbers and reports:
- "How many products are in stock, how many units are in the warehouse, and what's our average price?"
- "Put the names of the out-of-stock products in one line for the morning email."
- "Show each category with its products under it, and how many each one has."
- "Which products were ordered today, each one once?"
Sorting, Cutting and Checking Streams covered putting a list in order, cutting it into pages and asking it yes-or-no questions. This lesson covers the other jobs: counting and doing math, collecting the results into a String or into groups, and turning a list of lists into one stream. It ends by reading a whole stream, step by step. As before, for each function you'll see the loop you would write without it, where that loop gets clumsy, and the function that does the same job.
The products, again
The examples use the same eight products as Sorting, Cutting and Checking Streams. Each one is a Product object with a name, a category, a price and the units in stock, read with the getters getProductName(), getCategoryName(), getUnitPrice() (a double) and getUnitsInStock() (an int). The constructor takes them in that order:
List<Product> products = new ArrayList<>();
products.add(new Product("Chai", "Beverages", 18.00, 39));
products.add(new Product("Chang", "Beverages", 19.00, 17));
products.add(new Product("Aniseed Syrup", "Condiments", 10.00, 13));
products.add(new Product("Chef Anton's Gumbo Mix", "Condiments", 21.35, 0));
products.add(new Product("Ikura", "Seafood", 31.00, 31));
products.add(new Product("Konbu", "Seafood", 6.00, 24));
products.add(new Product("Tofu", "Produce", 23.25, 35));
products.add(new Product("Alice Mutton", "Meat/Poultry", 39.00, 0));
| Product | Category | Price | Units in stock |
|---|---|---|---|
| Chai | Beverages | 18.00 | 39 |
| Chang | Beverages | 19.00 | 17 |
| Aniseed Syrup | Condiments | 10.00 | 13 |
| Chef Anton's Gumbo Mix | Condiments | 21.35 | 0 |
| Ikura | Seafood | 31.00 | 31 |
| Konbu | Seafood | 6.00 | 24 |
| Tofu | Produce | 23.25 | 35 |
| Alice Mutton | Meat/Poultry | 39.00 | 0 |
Two of them, Chef Anton's Gumbo Mix and Alice Mutton, are out of stock.
The examples use method references such as Product::getUnitPrice, read "Product's getUnitPrice method". A method reference means the same as a lambda that only calls that method, here product -> product.getUnitPrice().
Counting and math: count, sum, average, min and max
When you'll use it: dashboards and reports: how many orders today, the total of a cart, a class's average grade, the highest score.
count: how many?
How many products are in stock? A loop would keep a counter and add one each time. count() does the counting:
long inStock = products.stream()
.filter(product -> product.getUnitsInStock() > 0)
.count();
// inStock is 6
count() gives back a long, not an int. A long is a whole number like an int, with room for much bigger values, because a stream could hold more items than an int can count. Store the answer in a long.
mapToInt and sum: adding numbers up
How many units are in the warehouse? In Common Stream Functions you added numbers up with reduce, and it works here too:
int totalUnits = products.stream()
.map(Product::getUnitsInStock)
.reduce(0, (total, units) -> total + units);
// totalUnits is 159
There's a shorter way. A stream of products can't add products together: what would Chai plus Chang even be? So first turn each product into a plain number with mapToInt. That gives you an IntStream, a stream of int values, and a stream of numbers has math built in: sum(), average(), min() and max().
int totalUnits = products.stream()
.mapToInt(Product::getUnitsInStock)
.sum();
// totalUnits is 159
It's like going from a cart of groceries to the receipt: once each item is a number, adding them up is one step. For prices, which are double values, use mapToDouble, which gives a DoubleStream with the same math.
average: the box might be empty
What's the average price?
double averagePrice = products.stream()
.mapToDouble(Product::getUnitPrice)
.average()
.orElse(0.0);
// averagePrice is 20.95
average() gives back an OptionalDouble: an Optional for a double. An Optional is a box that holds one value or nothing, the box findFirst gives back in Sorting, Cutting and Checking Streams. The average of an empty list doesn't exist (you can't divide by zero items), so the box might be empty. orElse(0.0) says what to use then: the value inside, or else 0.0. sum() needs no box: the sum of no numbers is 0.
min and max: the number, or the whole product
There are two ways to find the highest or lowest, depending on what you need back.
When you need only the number, map to numbers first. max() gives an OptionalDouble, for the same reason average() does:
double highestPrice = products.stream()
.mapToDouble(Product::getUnitPrice)
.max()
.orElse(0.0);
// highestPrice is 39.0
When you need the whole product, such as its name for the page, give min or max a comparator, the same kind sorted takes in Sorting, Cutting and Checking Streams. It gives back an Optional<Product>:
Optional<Product> cheapest = products.stream()
.min(Comparator.comparing(Product::getUnitPrice));
if (cheapest.isPresent())
{
System.out.println(cheapest.get().getProductName());
}
Konbu
isPresent() asks "is there something in the box?", and get() takes it out. Only call get() after checking: on an empty Optional, get() stops the program with a NoSuchElementException.
Collecting the results: collect and Collectors
When you'll use it: building a line of text for an email or a CSV file, and grouping data for a report or a page with headings.
So far, every stream has ended with toList() or with a single value. collect(...) is the general way to end a stream: you hand it a collector, a recipe for building the result. The Collectors class is a box of ready-made recipes. (toList() is a shortcut for the most common one.) Collectors lives in the java.util.stream package, so the file needs import java.util.stream.Collectors;.
Collectors.joining: one String, with separators
The morning email needs the out-of-stock products in one line, separated by commas. The loop version has a classic problem:
String names = "";
for (Product product : products)
{
names += product.getProductName() + ", ";
}
// names ends with "Tofu, Alice Mutton, ": one comma too many
Every name gets a comma after it, including the last one. To fix it, you'd add an if that treats the first or the last name differently. Collectors.joining(", ") puts the separator between the items, never after the last:
String outOfStock = products.stream()
.filter(product -> product.getUnitsInStock() == 0)
.map(Product::getProductName)
.collect(Collectors.joining(", "));
// outOfStock is "Chef Anton's Gumbo Mix, Alice Mutton"
joining works on a stream of String values, so map turns each product into its name first. On an empty stream, it gives an empty String, "".
Collectors.groupingBy: a group for each category
The category page shows a heading for each category with its products under it. That needs the products sorted into groups, one per category: Beverages in one pile, Condiments in another.
The result is a Map, a lookup table. Each key (here, a category name) leads to one value (here, the list of that category's products). Maps get a full lesson of their own, Maps, in the next chapter. For now, you need two things: the type is written Map<String, List<Product>> (a map from String keys to lists of products), and get(key) looks up one key's value.
By hand, you'd make an empty list for each category you meet, check whether it already exists, and add each product to the right one. groupingBy does all of that. You tell it what to group by:
Map<String, List<Product>> byCategory = products.stream()
.collect(Collectors.groupingBy(Product::getCategoryName));
List<Product> seafood = byCategory.get("Seafood");
// seafood holds Ikura and Konbu, in the order they were in products
Collectors.counting: how many in each group
Often you want a number per group, not the whole list. Give groupingBy a second recipe, Collectors.counting(), and each group is counted instead:
Map<String, Long> countByCategory = products.stream()
.collect(Collectors.groupingBy(Product::getCategoryName, Collectors.counting()));
System.out.println(countByCategory.get("Condiments"));
System.out.println(countByCategory.get("Dairy Products"));
System.out.println(countByCategory);
2
null
{Produce=1, Meat/Poultry=1, Seafood=2, Beverages=2, Condiments=2}
Three things to notice:
- The counts are
Longvalues, becausecounting()counts the waycount()does. - A key that isn't in the map, such as
"Dairy Products", givesnull. A category with no products gets no group at all. - The map doesn't keep the order the products came in. That's how this kind of map works, and Maps explains why.
When the items are already the labels you want to count, such as a list of category names, group by the item itself: Collectors.groupingBy(category -> category, Collectors.counting()) gives each different name as a key, with how many times it appears.
flatMap: a list of lists becomes one stream
When you'll use it: whenever each item holds a list of its own: orders with their order lines, students with their courses, posts with their tags.
Each order the store takes is a list of product names, so the day's orders are a list of lists. The type is written List<List<String>>, read "a list of lists of strings". (List.of(...) makes a list filled with the values in the parentheses, one you can't change afterward.)
List<List<String>> todaysOrders = List.of(
List.of("Chai", "Tofu"),
List.of("Chang"),
List.of("Chai", "Konbu", "Ikura"));
The warehouse asks: which products were ordered today, each one once? With loops, you'd need one loop inside another, plus a check for repeats:
List<String> productsOrdered = new ArrayList<>();
for (List<String> order : todaysOrders)
{
for (String productName : order)
{
if (!productsOrdered.contains(productName))
{
productsOrdered.add(productName);
}
}
}
map can't help here. It turns each item into exactly one new thing, so mapping three orders gives you three things, still one per order. What you want is to tip each order's products out into one stream, like emptying three shopping bags onto one counter. That's flatMap: you give it a lambda that turns each item into a stream, and it pours all of those streams into one.
List<String> productsOrdered = todaysOrders.stream()
.flatMap(order -> order.stream())
.distinct()
.sorted()
.toList();
// productsOrdered contains [Chai, Chang, Ikura, Konbu, Tofu]
After flatMap, the stream holds six names (Chai, Tofu, Chang, Chai, Konbu, Ikura), and from there it's the stream functions you already know: distinct drops the second Chai, and sorted puts them in order.
Reading a whole stream: intermediate and terminal operations
Real streams string several of these steps together. Here's the out-of-stock line for the email again, now in alphabetical order:
String outOfStockReport = products.stream()
.filter(product -> product.getUnitsInStock() == 0)
.sorted(Comparator.comparing(Product::getProductName))
.map(Product::getProductName)
.collect(Collectors.joining(", "));
// outOfStockReport is "Alice Mutton, Chef Anton's Gumbo Mix"
Every step in it is one of two kinds:
- An intermediate operation gives back another stream, so another step can follow it:
filter,map,sorted,distinct,limit,skip,flatMap,mapToIntandmapToDouble. - A terminal operation ends the stream and gives back a result: a list, a
String, a number, aboolean, anOptionalor a map.toList,collect,count,sum,average,min,max,anyMatch,allMatch,noneMatch,findFirst,forEachandreduceare terminal.
A whole stream, from its source through its steps to its one terminal operation, is called a stream pipeline. Reading a pipeline means reading the intermediate steps in order, then asking "what does the terminal operation give back?". That answer is the type of the variable on the left.
A stream can be used only once. After its terminal operation, it's finished, and using the same stream again stops the program with an IllegalStateException that says stream has already been operated upon or closed. That's why every example starts a fresh one with products.stream().
Here are the functions from this lesson and Sorting, Cutting and Checking Streams in one table, by the job they do:
| The job | The function | Gives back |
|---|---|---|
| Put items in order | sorted(Comparator.comparing(...)), .reversed(), .thenComparing(...) |
a stream (intermediate) |
| Keep the first few | limit(n) |
a stream (intermediate) |
| Drop the first few | skip(n) |
a stream (intermediate) |
| Is there at least one? | anyMatch(...) |
boolean |
| Does every item match? | allMatch(...) |
boolean |
| Does no item match? | noneMatch(...) |
boolean |
| The first item, if any | findFirst(), then orElse(...) |
Optional |
| How many | count() |
long |
| Total, average | mapToInt(...) or mapToDouble(...), then sum() or average() |
a number, or OptionalDouble |
| Highest or lowest | max(...), min(...) |
Optional, or OptionalDouble after mapToDouble |
| One String | collect(Collectors.joining(", ")) |
String |
| Groups | collect(Collectors.groupingBy(...)) |
Map |
| A count per group | collect(Collectors.groupingBy(..., Collectors.counting())) |
Map of Long counts |
| A list of lists as one stream | flatMap(...) |
a stream (intermediate) |
Do it: make the warehouse pick list
Every morning the warehouse gets the day's orders, and each order is a list of product names. A product can be in several orders, and more than once in the same order (a shopper who wants two boxes of Chai has Chai on their order twice). Before anyone walks the shelves, the warehouse wants a pick list: each product once, with how many to pick in all.
The method gets one value:
orders: the day's orders, aList<List<String>>. Each order is aList<String>of product names. An order can be empty.
For example, pickList(orders) with these three orders:
List<List<String>> orders = List.of(
List.of("Chai", "Tofu"),
List.of("Chang"),
List.of("Chai", "Konbu", "Chai"));
| Step | The product names |
|---|---|
| The three orders | [Chai, Tofu], [Chang], [Chai, Konbu, Chai] |
| Every name from every order, in one stream | Chai, Tofu, Chang, Chai, Konbu, Chai |
| A group for each name, counted | Chai: 3, Tofu: 1, Chang: 1, Konbu: 1 |
So it returns a map in which "Chai" leads to 3, and "Tofu", "Chang" and "Konbu" each lead to 1. A map doesn't keep an order, so any order of those four is right.
Your job: write the method pickList(List<List<String>> orders) so it returns a Map<String, Long>: each product name, and how many times it appears in all the orders together.
- Every product name in any order is a key, once.
- Its value is how many times the name appears across all the orders, as a
Long. - An empty order adds nothing.
- When there are no orders, or every order is empty, return an empty map.
Practiced live on the lesson page: write the Java right there and check it.
Check yourself
2 questions to try on the lesson page.
So what
Counting, totaling, joining, grouping and flattening cover the reports and summaries most applications need, and once you can read a pipeline as intermediate steps and one terminal step, you can read any stream you meet in someone else's code.
Sources
- Oracle, Stream (Java SE 25 & JDK 25): the API reference for
count,min,max,mapToInt,mapToDouble,flatMapandcollect, and the definitions of intermediate and terminal operations. - Oracle, IntStream (Java SE 25 & JDK 25): the API reference for
sum,average,minandmaxon a stream of numbers. - Oracle, Collectors (Java SE 25 & JDK 25): the API reference for
joining,groupingByandcounting. - Oracle, Optional (Java SE 25 & JDK 25): the API reference for
isPresent,getandorElse.