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 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.

Chaand Sheikh

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

What you will learn

  • Build a stream pipeline from a source, stations and a terminal
  • Keep values with filter and change them with map
  • Sort or count what's left, and see that the source list doesn't change
  • Fold many values into one with reduce

Before you start

  • Java lambdas and functional interfaces
  • Java built-in functional interfaces

Think of a stream as a conveyor belt with stations. The values ride the belt, and each station does one small job. Every station takes a lambda.

A belt with stations

package org.studyeasy.s05l09;

import java.util.List;

public class Ex01_FirstPipeline {
    public static void main(String[] args) {
        List<Integer> numbers = List.of(4, 7, 2, 9, 5);

        List<Integer> result = numbers.stream()
                .filter(n -> n > 4)     // keep 7, 9 and 5
                .map(n -> n * 10)       // change each one
                .toList();              // collect into a new list

        System.out.println(result);
    }
}
[70, 90, 50]
The source numbers.stream() puts 4, 7, 2, 9, 5 on a belt. The filter station asks n greater than 4: 4 and 2 drop out, 7, 9, 5 go on. The map station multiplies by 10 giving 70, 90, 50. The terminal toList collects them into a new list. sourcenumbers.stream() filtern > 4 ? mapn * 10 toListterminal 4 7 2 9 5 7 9 5 70 90 50 [70, 90, 50] 4 and 2 fail the test and drop out
filter drops, map changes, toList collects.

A pipeline has three parts. numbers.stream() is the source: it puts the list on the belt. filter and map are stations. Filter asks each value a true-or-false question and keeps only the ones that pass; map changes each value that reaches it. toList() is the terminal: it ends the chain and collects what's left into a new list. Each dot hands the result to the next call, which is called chaining. Leave off toList() and it won't compile: a Stream isn't a List.

Sort what is left, or count it

List<Integer> scores = List.of(72, 91, 58, 85);

List<Integer> passed = scores.stream()
        .filter(s -> s >= 60)   // 58 is gone
        .sorted()               // smallest first
        .toList();
System.out.println(passed);

long count = scores.stream().filter(s -> s >= 60).count();
System.out.println("Passed: " + count);
System.out.println("Original: " + scores);
[72, 85, 91]
Passed: 3
Original: [72, 91, 58, 85]

The filter drops 58. sorted() with no comparator puts the rest smallest first. A second chain ends with count() instead, which returns a number; it's a long, so int bad = ...count(); won't compile. And note the last line: scores didn't change. Each chain builds a new result and leaves the source alone. (The name s is just a local name; any name works.)

Fold many values into one

package org.studyeasy.s05l09;

import java.util.List;

public class Ex03_Reduce {
    public static void main(String[] args) {
        List<Integer> cart = List.of(499, 1299, 250, 799);

        // start at 0, then fold each price into the running sum
        int bill = cart.stream().reduce(0, (sum, price) -> sum + price);
        System.out.println("Total: " + bill);

        // filter first, then add up what is left
        int premium = cart.stream()
                .filter(p -> p > 500)
                .reduce(0, (sum, p) -> sum + p);
        System.out.println("Premium: " + premium);
    }
}
Total: 2847
Premium: 2098

reduce folds many values into one, like adding up a bill. 0 is the start value, sum is the total so far and price is the current one:

Pricesum + price
4990 + 499 = 499
1299499 + 1299 = 1798
2501798 + 250 = 2048
7992048 + 799 = 2847

In the second block, the filter drops 499 and 250 first, so only 1299 and 799 reach the sum: 2098. You can filter first and then reduce only what passed. reduce gives back an Integer, so assigning it to a String won't compile.

Recap

PartExamplesJob
Sourcelist.stream()puts values on the belt
Stationsfilter, map, sorteddrop, change or order values
TerminaltoList, count, reduceends the chain with a result

The notation looks odd at first, especially reduce, but once you picture the belt it's simple. Next: grouping and collecting in Streams II.

Keep going in Java · 63 of 79

Previous
Java Optional: Saying Maybe Without null
Next post
Java Streams II: Collectors, groupingBy and flatMap
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 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.

On this page

  • A belt with stations
  • Sort what is left, or count it
  • Fold many values into one
  • 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.