Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

Java
  • Install Java 25 (JDK) and IntelliJ IDEA, Then Run Your First Program
  • Use Claude Agent, Copilot or Junie Inside IntelliJ IDEA
  • Java Hello World with Maven: What the JDK Does and What Maven Adds
  • Java Variables, Keywords and Naming Rules
  • Maven in IntelliJ: pom.xml, Dependencies and the Build Lifecycle
  • Java Primitive Types and Memory: What int x = 5 Really Does
  • Java Strings and Text Blocks: Quotes, Concatenation and parseInt
  • Java Operators: Arithmetic, a++ vs ++a, Precedence, && || and the Ternary
  • Java Type Casting: Widening, Narrowing and Converting Text to Numbers
  • Java Practice Lab: A Cafe Bill with Variables, Operators and Casting
  • Java if, else and switch: Braces, Else-If Ladders and the Modern Switch
  • Java Loops: for, while, do-while and for-each
  • Java break, continue and Nested Loops
  • What's New in Java 21 to 25: Compact Source Files and Sequenced Collections
  • Java Arrays: Indexes, Default Values, Loops and 2D Grids
  • Java Methods and Overloading: Parameters, return and Pass-by-Value
  • Java Scope, Code Blocks and the Call Stack
  • Read User Input in Java with Scanner (and the Leftover Enter Trap)
  • Java Practice Lab: A Gym Weekly Tracker with Loops, Arrays and Methods
  • Debugging Java in IntelliJ: Stack Traces, Breakpoints and a Better AI Prompt
  • Java var: Let Java Infer the Type
  • Push and Pull in IntelliJ: Two Developers, One GitHub Repository, a Rejected Push and a Conflict
  • Java Classes and Objects: One Blueprint, Many Cars
  • Java Constructors and the this Keyword
  • Java Instance Methods, Getters, Setters and toString
  • Java static: Fields, Methods and Blocks Shared by the Whole Class
  • Java Packages and Imports: Every Class Has an Address
  • Java Access Modifiers and Encapsulation: Private Data, Public Methods
  • Java final and Immutable Objects: Assign Once, Share Safely
  • Java Strings as Objects: The String Pool, == vs equals, StringBuilder and printf
  • Java Practice Lab: A Library Book Catalogue with final Fields and StringBuilder
  • Java Inheritance: extends, super and the Order Objects Are Built
  • Java Method Overriding, @Override and the Object Class
  • Java Polymorphism: Upcasting, Dynamic Dispatch and Downcasting
  • Java Composition: Has-A vs Is-A
  • Java Abstract Classes: A Parent That Leaves One Blank
  • Java Interfaces: Contracts and Multiple Inheritance
  • Java Nested, Inner and Anonymous Classes
  • Java Enums with Fields, Methods and switch
  • Java Practice Lab: Payment Processing with an Interface, an Abstract Class and an Enum
  • Java Records: A Whole Data Class in One Line
  • Java Sealed Classes and Interfaces
  • Java Pattern Matching with instanceof and switch
  • Java Record Patterns: Unpacking a Record
  • Java equals and hashCode: Why a HashSet Needs Both
  • From Arrays to Collections: The Java Collections Framework Map
  • Java Wrapper Classes and Autoboxing
  • Java ArrayList: The Stretchy Array
  • Java LinkedList vs ArrayList: Nodes or an Array
  • Java Sets: HashSet, LinkedHashSet and TreeSet
  • Java Sorting with Comparable and Comparator
  • Java Maps: HashMap, LinkedHashMap and TreeMap
  • Java Stacks, Queues and Deques: ArrayDeque and PriorityQueue
  • Choosing a Java Collection: Immutable and Sequenced Collections
  • Java Exception Handling: try, catch and finally
  • Java throw, throws, Checked vs Unchecked and Custom Exceptions
  • Java try-with-resources and Clean Error Handling
  • Java Generics: Type-Safe Containers
  • Java Generic Methods, Bounded Types and Wildcards
  • Java Lambdas and Functional Interfaces
  • Java Built-in Functional Interfaces: Predicate, Function, Consumer, Supplier
  • Java Optional: Saying Maybe Without null
  • Java Streams I: filter, map and reduce
  • Java Streams II: Collectors, groupingBy and flatMap
  • Why Concurrency: Processes, Threads and the Main Thread in Java
  • Creating Threads in Java: Thread, Runnable and Lambdas
  • Java Thread Lifecycle: sleep, join and interrupt
  • Java Race Conditions and synchronized
  • Java volatile and Atomic Variables
  • Java ExecutorService and Thread Pools
  • Java Callable, Future and CompletableFuture
  • Java Locks, Deadlock and tryLock
  • Java Concurrent Collections and Virtual Threads
  • Why Slow Work Belongs off the Request Thread: 202 Accepted and a Job Id in Spring Boot
  • Virtual Threads in Spring Boot: One Property, and the Connection Pool Trap
  • @Async, Named TaskExecutors and Structured Concurrency in Spring Boot
  • Java Files and Directories with NIO.2: Path and Files
  • Reading and Writing Text Files in Java
  • Java Structured Data: Reading and Writing JSON and CSV
  1. Blog
  2. /
  3. Java
  4. /
  5. Lambdas and Streams

Java Streams II: Collectors, groupingBy and flatMap

Six sales feed every example. toList and joining give [Emma, Jake, Sofia] and "North / South / West", groupingBy with counting and summingInt gives a count and a total per region, flatMap pours three orders' items into one list, and mapToInt sums 5400.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Lambdas and Streams

What you will learn

  • Collect a stream into a List or one joined String
  • Group items into a Map with groupingBy, then count or sum each group
  • Flatten a list of lists with flatMap
  • Add up a field with mapToInt and sum, and know when a plain loop is clearer

Before you start

  • Java streams I: filter, map and reduce
  • Java records

This time we collect stream results into a List, a String or a Map. Every example starts from the same six sales.

Meet the data: six sales

package org.studyeasy.s05l10;

import java.util.List;

// One sale: who sold it, in which region, and for how much
public record Sale(String rep, String region, int amount) {
    // Our data set: these six sales feed every example
    public static List<Sale> ledger() {
        return List.of(
                //        rep     region  amount
                new Sale("Emma", "North", 1200),
                new Sale("Liam", "South", 800),
                new Sale("Anna", "North", 450),
                new Sale("Jake", "West", 1500),
                new Sale("Sofia", "South", 950),
                new Sale("Mark", "North", 500));
    }

    // Short toString, so a printed List or Map of sales stays readable
    @Override
    public String toString() {
        return rep + " " + amount;
    }
}

A record with a rep, a region and an amount, plus a static ledger() that hands back the six sales across North, South and West.

Collect into a List or a String

List<String> bigSellers = Sale.ledger().stream()
        .filter(s -> s.amount() >= 900)  // keep 900 or more
        .map(s -> s.rep())               // keep just the name
        .toList();

String team = Sale.ledger().stream()
        .map(s -> s.rep())
        .collect(Collectors.joining(", "));

String regions = Sale.ledger().stream()
        .map(s -> s.region())
        .distinct().sorted()
        .collect(Collectors.joining(" / "));
Big sellers: [Emma, Jake, Sofia]
Team: Emma, Liam, Anna, Jake, Sofia, Mark
Regions: North / South / West

toList gives a List (a read-only one: bigSellers.add("Zoe") throws UnsupportedOperationException). Collectors.joining(", ") glues Strings into one, putting the separator only between names, so there's no comma after Mark. Any separator works. distinct keeps each region once and sorted orders them first.

Sort the sales into buckets

// 1. groupingBy: one List of sales per region
Map<String, List<Sale>> byRegion = Sale.ledger().stream()
        .collect(Collectors.groupingBy(s -> s.region()));
System.out.println("In North: " + byRegion.get("North").size());
System.out.println("By region: " + byRegion);

// 2. counting(): how many sales in each region
Map<String, Long> counts = Sale.ledger().stream()
        .collect(Collectors.groupingBy(s -> s.region(),
                Collectors.counting()));

// 3. summingInt(): add up the amounts in each region
Map<String, Integer> totals = Sale.ledger().stream()
        .collect(Collectors.groupingBy(s -> s.region(),
                Collectors.summingInt(s -> s.amount())));
In North: 3
By region: {West=[Jake 1500], South=[Liam 800, Sofia 950], North=[Emma 1200, Anna 450, Mark 500]}
Counts: {West=1, South=2, North=3}
Totals: {West=1500, South=1750, North=2150}
Six sales arrive in ledger order and the lambda s.region() gives each a key. groupingBy makes a bucket the first time a key appears and drops later sales into the existing bucket. North holds Emma 1200, Anna 450, Mark 500: count 3, sum 2150. South holds Liam 800 and Sofia 950: count 2, sum 1750. West holds Jake 1500: count 1, sum 1500. Emma N, Liam S, Anna N, Jake W, Sofia S, Mark N North Emma 1200, Anna 450,Mark 500 South Liam 800, Sofia 950 West Jake 1500 counting 3, sum 2150 counting 2, sum 1750 counting 1, sum 1500
Every sale lands in the bucket for its key; the second collector reports on each bucket.

groupingBy(s -> s.region()) makes the lambda's result the key and collects each region's sales into a List. Emma opens the North bucket; Anna finds it already there and joins her. A second collector changes what each bucket reports: counting() gives how many (as a Long), summingInt adds the amounts. groupingBy builds a HashMap, so the region order in the printout isn't promised.

Open the lists inside a list

// An order holds a List of items: a list inside a list
record Order(String customer, List<String> items) {}

List<Order> orders = List.of(
    new Order("Sarah", List.of("Laptop", "Mouse")),
    new Order("Chris", List.of("Monitor")),
    new Order("Chloe", List.of("Mouse", "Keyboard", "Webcam")));

List<List<String>> nested =
        orders.stream().map(o -> o.items()).toList();

List<String> items = orders.stream()
        .flatMap(o -> o.items().stream()).toList();

List<String> toStock = items.stream().distinct().sorted().toList();
map:     [[Laptop, Mouse], [Monitor], [Mouse, Keyboard, Webcam]]
flatMap: [Laptop, Mouse, Monitor, Mouse, Keyboard, Webcam]
To stock: [Keyboard, Laptop, Monitor, Mouse, Webcam]

map keeps the boxes: each order becomes its whole List, so you get a list of three lists. flatMap opens them: each List becomes a stream, and the six items pour into one flat stream, Mouse twice. Now it's a normal stream, so distinct drops the second Mouse and sorted goes A to Z.

The report, and when a loop is clearer

int total = Sale.ledger().stream()
        .mapToInt(s -> s.amount()).sum();

// a running total changes every pass: a plain loop is clearer
int running = 0;
for (Map.Entry<String, Integer> e : byRegion.entrySet()) {
    running += e.getValue();   // add this region's total
    System.out.println(e.getKey() + " " + e.getValue()
            + ", running " + running);
}
Total: 5400
By region: {West=1500, South=1750, North=2150}
West 1500, running 1500
South 1750, running 3250
North 2150, running 5400

mapToInt turns each Sale into its int amount, and sum adds them: 5400. (Here byRegion is the summingInt map from before.) A stream handles each item on its own. A running total carries a value from pass to pass, so a plain loop is clearer.

Recap

WantUse
a ListtoList()
one Stringcollect(Collectors.joining(", "))
a Map of groupsgroupingBy(key), plus counting() or summingInt(...)
one stream from many listsflatMap(o -> o.items().stream())
a sum of a fieldmapToInt(...).sum()

Pick the container, and let collect fill it.

Keep going in Java · 64 of 79

Previous
Java Streams I: filter, map and reduce
Next post
Why Concurrency: Processes, Threads and the Main Thread in Java
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE

Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)

Related posts

Java Lambdas and Functional Interfaces

A six-line anonymous Discount becomes total -> total * 0.85. Lambdas with no, one and two parameters show which brackets and braces can go, a Runnable job runs between START and DONE, and two Comparator lambdas sort students by marks, then by name.

Java Built-in Functional Interfaces: Predicate, Function, Consumer, Supplier

Four ready-made sockets for lambdas: Predicate tests 20 >= 18, Function turns 5 into 15, Consumer prints Hello, Priya, Supplier hands back Monday. Then isPositive.and(isEven), isEven.negate() and multiply.andThen(addFive), which turns 3 and 4 into 17.

Java Optional: Saying Maybe Without null

A phone book returns null for Omar and the next .length() crashes. Optional.ofNullable gives a box instead: Optional[555-1234] or Optional.empty. orElse hands over "no number", ifPresent runs only for Asha, and map adds +1 only when there's a number.

Java Streams I: filter, map and reduce

Picture a conveyor belt: 4, 7, 2, 9, 5 ride through filter(n -> n > 4) and map(n -> n * 10) and come out as [70, 90, 50]. Then sorted and count on exam scores, and reduce folding a cart of 499, 1299, 250 and 799 into a 2847 bill.

On this page

  • Meet the data: six sales
  • Collect into a List or a String
  • Sort the sales into buckets
  • Open the lists inside a list
  • The report, and when a loop is clearer
  • Recap
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE

Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.