Lesson 21 of 23

In progress

Course progress

Java

Streams and lambdas

Replace loops with filter, map and collect, understand laziness, and know when a plain loop is clearer.

A stream is a pipeline: a source, a series of operations, and a terminal step that produces a result. It reads as a description of the transformation rather than a set of instructions for doing it.

What you will learn

  • Build a pipeline with filter, map and collect.
  • Use reduce, sorted and the numeric streams.
  • Know when a loop is the better choice.

A first pipeline

import java.util.List;
import java.util.stream.Collectors;
record Product(String name, long pricePaise, boolean inStock) { }
public class StreamsDemo {
public static void main(String[] args) {
List<Product> products = List.of(
new Product("pen", 2_000L, true),
new Product("lamp", 120_000L, false),
new Product("book", 45_000L, true)
);
List<String> names = products.stream()
.filter(Product::inStock)
.map(Product::name)
.map(String::toUpperCase)
.toList();
System.out.println(names);   // [PEN, BOOK]
}
}

Each step takes a stream and returns a stream. toList() is terminal: nothing runs until it is called. That laziness is what allows the library to combine steps and short-circuit where it can.

stream() on a collection starts a pipeline; toList() ends it. Between them, no data is copied.

The common operations

long total = products.stream()
.filter(Product::inStock)
.mapToLong(Product::pricePaise)
.sum();
System.out.println(total);
  • filter keeps elements matching a predicate.
  • map transforms each element.
  • mapToLong, mapToInt, mapToDouble produce primitive streams with sum, average, max.
  • sorted orders, optionally with a comparator.
  • distinct removes duplicates by equals.
  • limit and skip slice.
  • count returns the number of elements.

Collectors offers grouping and joining:

var byFirstLetter = products.stream()
.collect(Collectors.groupingBy(p -> p.name().substring(0, 1)));
String joined = products.stream()
.map(Product::name)
.collect(Collectors.joining(", "));

reduce

long cheapest = products.stream()
.mapToLong(Product::pricePaise)
.min()
.orElse(0L);

min and max return Optional because the stream may be empty. reduce combines elements with a function:

String all = products.stream()
.map(Product::name)
.reduce("", (a, b) -> a.isEmpty() ? b : a + ", " + b);

For string concatenation, Collectors.joining is clearer and linear. reduce is the general tool; reach for a specialised collector when one exists.

Laziness and short-circuiting

boolean anyExpensive = products.stream()
.filter(Product::inStock)
.anyMatch(p -> p.pricePaise() > 100_000L);

anyMatch stops at the first match, so a million-element stream may examine two elements. That is the benefit of laziness, and it means a stream with side effects can surprise you: a peek or a map that prints may run fewer times than expected.

Lambdas and method references

products.removeIf(p -> !p.inStock());          // lambda
products.sort(java.util.Comparator.comparing(Product::name));  // method reference

A lambda implements a functional interface: one abstract method, such as Predicate<T>, Function<T,R> or Comparator<T>. A method reference is shorthand when the lambda only calls one method.

Keep lambdas short. A lambda with three statements and a nested condition should be a named method, both for readability and because it can be tested.

Side effects and streams

A stream should transform data, not mutate external state. This is legal and bad:

List<String> seen = new java.util.ArrayList<>();
products.stream().forEach(p -> seen.add(p.name()));

The loop version is shorter and clearer. Use collect or toList to build a collection; leave forEach for a genuine terminal action such as printing or saving.

Parallel streams

long count = products.parallelStream().filter(Product::inStock).count();

Parallelism helps only for large collections with expensive, independent work. For small data the coordination costs more than it saves, and shared mutable state makes the result wrong. Measure before using it, and prefer explicit concurrency when the work is genuinely heavy.

When a loop is better

Streams read well for a sequence of transformations. They read badly when:

  • The body needs several statements or early continues.
  • The pipeline indexes into parallel arrays.
  • The logic mutates something as it goes.
  • The reader has to trace types through four operations to see what happens.

A for loop is not a legacy construct; it is the clearer choice for step-by-step work with state.

A worked example

var priceByFirstLetter = products.stream()
.filter(Product::inStock)
.collect(Collectors.groupingBy(
p -> p.name().substring(0, 1).toUpperCase(),
Collectors.summingLong(Product::pricePaise)));
priceByFirstLetter.forEach((letter, total) ->
System.out.println(letter + ": " + total / 100.0));

Read it as: keep in-stock products, group by first letter, sum the prices in each group. The equivalent loop needs a map, a null check and an update per element, which is the code groupingBy exists to replace.

Calling a terminal operation twice on the same stream. A stream can be consumed once; the second call throws IllegalStateException. Store the result or build a new stream.

Given a list of orders with a customer name and an amount, produce a map from customer to total amount, sorted by total descending, for amounts above 50000 paise.

Show solution
import java.util.List; import java.util.Map; import java.util.stream.Collectors; record Order(String customer, long paise) { } List<Order> orders = List.of( new Order("Ana", 120_000L), new Order("Ravi", 30_000L), new Order("Ana", 90_000L), new Order("Meera", 65_000L) ); Map<String, Long> totals = orders.stream() .filter(o -> o.paise() > 50_000L) .collect(Collectors.groupingBy(Order::customer, Collectors.summingLong(Order::paise))); totals.entrySet().stream() .sorted(Map.Entry.<String, Long>comparingByValue().reversed()) .forEach(e -> System.out.println(e.getKey() + ": " + e.getValue() / 100.0));

The filter removes small orders before grouping, so Ravi disappears. summingLong adds the remaining amounts per customer, and sorting the entries after collection gives the descending order without needing a TreeMap.

Recap

  • A stream is a lazy pipeline ending in a terminal operation that produces a value.
  • filter, map, collect and the numeric streams cover most transformations.
  • Streams can only be consumed once; use a loop when the work is step by step.

Next, structuring a real Java project so the code has somewhere to go as it grows.

Are streams slower than loops?
Sometimes slightly, often similarly, and occasionally faster because of laziness. Choose for readability first.
Should every loop become a stream?
No. Streams suit transformations; loops suit stateful step-by-step work.

Progress is saved in this browser only. No account, no email.

Admin

About the author

Admin

Instructor and technical writer at tutorials.in

Writes beginner lessons for tutorials.in. Each lesson is checked against the language or tool documentation, and examples are run before publishing.

Reviewed by the editorial team before publishing. Last updated November 16, 2026.