Thuta Learning
Java
AdvancedProgrammingBeginner

Lambdas & Stream Pipelines

JavaLesson 2935 min

What you'll walk away with

  • Explain how a lambda implements the single abstract method of a functional interface such as Predicate, Function or Supplier
  • Use method references such as String::toUpperCase in place of lambdas
  • Predict from the output that intermediate operations do not run until a terminal operation is called
  • Transform and aggregate data with filter, map, toList, count, groupingBy and joining
  • Avoid reusing a stream and mutating shared state inside lambdas

Explain it simply

Explain it simply

Picture a stream as a conveyor belt in a factory. Items from a collection (the source) ride the belt through stations: one removes what you do not want (filter), one reshapes each item (map), and the last one packs the results into a box (collect). A lambda is the short instruction for one station, such as name -> name.length() >= 5.

The belt only starts moving once the packing station, the terminal operation, is attached; setting up stations alone does nothing. Each belt can run only once, and it never changes the original collection.

Problem → Why → Solution

The problem: the intent gets lost inside loops

Write "take the names with five or more letters, in uppercase" as a plain loop and the how-to details, creating a result list, looping, checking with if and calling add, bury what you actually wanted. Add two or three more conditions, a sort and a grouping, and you end up with nested loops and temporary variables.

People new to streams also fall into a trap: using the same stream variable twice throws IllegalStateException.

Main.java
import java.util.List;
import java.util.stream.Stream;

public class Main {
  public static void main(String[] args) {
    Stream<String> names = List.of("ada", "grace", "linus").stream();
    long longNames = names.filter(n -> n.length() >= 5).count();
    long shortNames = names.filter(n -> n.length() < 5).count(); // IllegalStateException
    System.out.println(longNames + " " + shortNames);
  }
}

Why can't the stream be reused?

A stream is not a collection that stores data; it is a processing pipeline that passes over its source once. A terminal operation such as count() runs the pipeline and closes it, so a second use fails with "stream has already been operated upon or closed". The fix is to call names.stream() again for each calculation; the list itself is unchanged and can be streamed as many times as you like.

Core concept: a lazy pipeline built from lambdas

A lambda is an unnamed function written as (parameters) -> expression or (parameters) -> { statements }. Java has no separate function type, so a lambda is used as the implementation of an interface with exactly one abstract method, called a functional interface. The most common ones live in java.util.function: Predicate<T> (T to boolean), Function<T, R> (T to R), Consumer<T> (T to nothing) and Supplier<T> (nothing to T). The compiler works out which interface a lambda implements from its context; filter(), for example, expects a Predicate.

When a lambda only calls an existing method, a method reference is shorter: String::toUpperCase instead of s -> s.toUpperCase(), and System.out::println instead of x -> System.out.println(x). Method references come in four shapes: a static method (Integer::parseInt), a method on a specific object (System.out::println), an instance method of the parameter (String::length) and a constructor (ArrayList::new). A lambda may read local variables from the surrounding code, but only if they are final or effectively final, meaning they are never reassigned after their first assignment.

A stream pipeline has three parts. The source is where it starts, such as list.stream(). Intermediate operations such as filter, map, sorted, distinct and limit return a new stream and are lazy: calling them only records the work to be done. Data starts flowing only when you call a terminal operation such as toList, collect, count, forEach, findFirst or sum.

Items travel through the whole pipeline one at a time rather than operation by operation, so a short-circuiting operation like findFirst() stops checking the remaining items as soon as it has an answer. toList(), added in Java 16, returns an unmodifiable list, and a stream never changes its source collection.

Mental model: the last station starts the belt
  1. Source: list.stream()
  2. Intermediate ops are only recorded
  3. A terminal op starts the run
  4. Items flow through one by one
  5. Stream is closed; source unchanged

A pipeline without a terminal operation does no work at all.

General pattern

java
List<Result> results = source.stream()     // source
    .filter(item -> condition(item))       // intermediate (lazy)
    .map(Type::convert)                    // intermediate, method reference
    .toList();                             // terminal: runs the pipeline

Predicate<T> test = t -> ...;              // T -> boolean
Function<T, R> fn = t -> ...;              // T -> R
Map<K, List<T>> groups = source.stream()
    .collect(Collectors.groupingBy(t -> key(t)));

Take a stream from the source, chain intermediate operations and finish with exactly one terminal operation. Lambdas have functional interface types such as Predicate and Function, and Collectors.groupingBy gathers items into a Map by key.

Example: long names in uppercase

This pipeline keeps the names with five or more letters, converts them to uppercase and collects them into a new list. Reading it from top to bottom shows the intent directly: filter, then map, then make a list.

java
import java.util.List;

class Main {
    public static void main(String[] args) {
        List<String> names = List.of("ada", "grace", "linus");
        List<String> result = names.stream()
            .filter(name -> name.length() >= 5)
            .map(String::toUpperCase)
            .toList();
        System.out.println(result);
    }
}

Code breakdown

  1. Line 5List<String> names = List.of("ada", "grace", "linus");

    The source collection. List.of() creates an immutable list, which is fine because a stream never modifies its source.

  2. Line 6List<String> result = names.stream()

    stream() starts a new pipeline over the list. No item has been read yet.

  3. Line 7.filter(name -> name.length() >= 5)

    This lambda is a Predicate<String>; only items for which it returns true move on. "ada", with three letters, stops here.

  4. Line 8.map(String::toUpperCase)

    The method reference means the same as name -> name.toUpperCase(). As a Function<String, String> it turns each item into a new value.

  5. Line 9.toList();

    The terminal operation: only now does the pipeline run, returning [GRACE, LINUS] as an unmodifiable list. The names list is unchanged.

You should see
[GRACE, LINUS]

Functional interfaces and method references

You can also store lambdas in variables, which makes the functional interface types visible. A static method reference such as Main::isLong also fits Predicate. minLength is used inside a lambda and never reassigned, so it is effectively final; adding minLength++ anywhere would cause a compile error.

Main.java
import java.util.List;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;

public class Main {
  static boolean isLong(String s) {
    return s.length() >= 5;
  }

  public static void main(String[] args) {
    Predicate<String> longName = name -> name.length() >= 5;   // T -> boolean
    Function<String, Integer> length = String::length;          // T -> R
    Supplier<String> greeting = () -> "hello";                  // () -> T
    Predicate<String> sameRule = Main::isLong;                  // static method ref

    System.out.println(longName.test("grace") + " " + sameRule.test("ada"));
    System.out.println(length.apply("linus"));
    System.out.println(greeting.get());

    int minLength = 4;                     // effectively final: never reassigned
    List<String> kept = List.of("ada", "grace", "bob", "linus").stream()
        .filter(n -> n.length() >= minLength)
        .toList();
    System.out.println(kept);
  }
}

Watching laziness happen

The program below prints from inside filter and map. Nothing is printed while the pipeline is being built; work begins only when findFirst() is called, and once "grace" is found, "linus" and "barbara" are never checked. Finally, reusing that stream throws IllegalStateException.

Main.java
import java.util.List;
import java.util.stream.Stream;

public class Main {
  public static void main(String[] args) {
    List<String> names = List.of("ada", "grace", "linus", "barbara");

    Stream<String> pipeline = names.stream()
        .filter(n -> {
          System.out.println("filter " + n);
          return n.length() >= 5;
        })
        .map(n -> {
          System.out.println("map " + n);
          return n.toUpperCase();
        });
    System.out.println("pipeline built, nothing ran yet");

    String first = pipeline.findFirst().orElse("none");
    System.out.println("first = " + first);

    try {
      pipeline.count();                    // a stream can only be consumed once
    } catch (IllegalStateException e) {
      System.out.println("reuse: " + e.getMessage());
    }
  }
}

The output is pipeline built, nothing ran yet, then filter ada, filter grace, map grace, first = GRACE, and finally reuse: stream has already been operated upon or closed. Notice that map does not wait for every filter call to finish: "grace" goes straight from filter to map on its own.

Collectors: groupingBy, joining and primitive streams

collect() gathers the result using a recipe from Collectors. groupingBy() splits items into a Map by a key function, and passing TreeMap::new gives you a map with sorted keys. joining() glues strings together with a separator, and mapToInt() returns an IntStream that offers numeric operations such as sum() without boxing.

Main.java
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;

public class Main {
  public static void main(String[] args) {
    List<String> words = List.of("apple", "avocado", "banana", "blueberry", "cherry");

    Map<Character, List<String>> byLetter = words.stream()
        .collect(Collectors.groupingBy(
            w -> w.charAt(0), TreeMap::new, Collectors.toList()));
    System.out.println(byLetter);

    int totalLetters = words.stream().mapToInt(String::length).sum();
    System.out.println("Total letters: " + totalLetters);

    String joined = words.stream()
        .sorted()
        .limit(3)
        .collect(Collectors.joining(", ", "[", "]"));
    System.out.println(joined);
  }
}

In real projects

Where this shows up in real projects

Service code uses streams to turn a list of database entities into a list of API response DTOs (map), to keep only active users (filter), and to group orders by status and total them (groupingBy with summingInt). Spring event listeners, comparators such as Comparator.comparing(User::getName), Optional's map and orElse, and CompletableFuture's thenApply all accept lambdas and method references, so you see this syntax everywhere.

Teams use streams for readability, and when a pipeline grows complicated they extract steps into named methods: .filter(this::isEligible) reads better than five conditions crammed into one lambda. They do not switch to parallelStream() just because there is a lot of data. It shares the common ForkJoinPool, which can slow other requests on a web server, and thread overhead often makes it slower for small inputs, so it is chosen only after a benchmark proves it helps.

Common mistakes

Common mistakes

1. Reusing a stream variable

Storing a stream in a variable and calling two terminal operations on it throws IllegalStateException on the second call. Do not keep streams in variables: call list.stream() again for each calculation, or use a Supplier<Stream<T>>.

2. Filling an outside list from forEach

stream().filter(...).forEach(x -> results.add(x)) works, but it mutates shared state. Switch to parallel and the non-thread-safe ArrayList can lose items or throw. Return the result with .toList() or collect() instead.

3. Trying to change a local variable inside a lambda

int count = 0; list.forEach(x -> count++); fails with "local variables referenced from a lambda expression must be final or effectively final". Use .count() to count and mapToInt(...).sum() to add up.

4. Forgetting the terminal operation

list.stream().map(this::save); is lazy, so save() is never called and no error appears. If you need side effects, use a plain for loop.

Mini challenge

Mini challenge: an order report

From a list of Order records, use streams to report each customer's paid total, the number of unpaid orders, the orders of 100 or more, and the top customer. Do not use loops, and do not modify the source list.

  • Sum paid orders per customer with groupingBy plus summingInt, sorted with a TreeMap
  • Count unpaid orders with filter plus count
  • Turn orders of 100 or more into strings like "Aye:120"
  • Find the customer with the highest paid total using max(Map.Entry.comparingByValue())
Main.java
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;

public class Main {
  record Order(String customer, int amount, boolean paid) {}

  public static void main(String[] args) {
    List<Order> orders = List.of(
        new Order("Aye", 120, true),
        new Order("Bo", 80, false),
        new Order("Aye", 40, true),
        new Order("Chit", 200, true),
        new Order("Bo", 60, true));

    // TODO: Map<String, Integer> paidTotals (sorted by customer)
    // TODO: long unpaid
    // TODO: List<String> bigOrders like "Aye:120"
    // TODO: String top customer by paid total
  }
}

Expected: The program should print: Paid totals: {Aye=160, Bo=60, Chit=200} Unpaid orders: 1 Big orders: [Aye:120, Chit:200] Top customer: Chit Source size unchanged: 5

Show hint

The three-argument groupingBy takes (key function, map factory, downstream collector): Order::customer, TreeMap::new, Collectors.summingInt(Order::amount). Record accessors such as paid() are methods, so Order::paid works directly as a Predicate.

Show solution
Main.java
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;

public class Main {
  record Order(String customer, int amount, boolean paid) {}

  public static void main(String[] args) {
    List<Order> orders = List.of(
        new Order("Aye", 120, true),
        new Order("Bo", 80, false),
        new Order("Aye", 40, true),
        new Order("Chit", 200, true),
        new Order("Bo", 60, true));

    Map<String, Integer> paidTotals = orders.stream()
        .filter(Order::paid)
        .collect(Collectors.groupingBy(
            Order::customer, TreeMap::new, Collectors.summingInt(Order::amount)));
    System.out.println("Paid totals: " + paidTotals);

    long unpaid = orders.stream().filter(o -> !o.paid()).count();
    System.out.println("Unpaid orders: " + unpaid);

    List<String> bigOrders = orders.stream()
        .filter(o -> o.amount() >= 100)
        .map(o -> o.customer() + ":" + o.amount())
        .toList();
    System.out.println("Big orders: " + bigOrders);

    String top = paidTotals.entrySet().stream()
        .max(Map.Entry.comparingByValue())
        .map(Map.Entry::getKey)
        .orElse("none");
    System.out.println("Top customer: " + top);
    System.out.println("Source size unchanged: " + orders.size());
  }
}

Quick quiz 1 / 3

What does List.of(1, 2, 3).stream().map(x -> { System.out.println(x); return x * 2; }); print when run?

Quick quiz 2 / 3

Which statement about the variable limit in filter(n -> n.length() > limit) is true?

Quick quiz 3 / 3

You use Collectors.groupingBy(Order::status) without a map factory and print the result. What is the key order?

What to remember

  • A lambda implements the single abstract method of a functional interface such as Predicate, Function, Consumer or Supplier, and a method reference is a shorter form.
  • A pipeline is a source, lazy intermediate operations and one terminal operation; nothing runs until the terminal operation.
  • A stream is single-use and never changes its source; toList() returns an unmodifiable list.
  • Gather results with collect or toList, do not mutate shared state from lambdas, and go parallel only after measuring.

Java Stream API — Oracle

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Lambdas & Stream Pipelines | Thuta Learning