Skip to content

Module 10 · Lambdas, Streams, Concurrency and JDBC — topic 2 of 5

The Streams API

Processing collections declaratively with streams: creating streams, filter/map/sorted/distinct/limit, terminal operations, collectors for grouping and joining, primitive streams and Optional.

Beginner 20 min read·Lesson 36 of 39 in Java Programming

Learning objectives

  • Build stream pipelines from collections, arrays and ranges
  • Use collectors to group, count, join and partition data
  • Use Optional results safely

Definition

A stream is a sequence of elements supporting a pipeline of lazy intermediate operations (filter, map, sorted …) ending in a terminal operation (collect, count, reduce …) that produces a result. Streams do not store data and do not modify their source.

Introduction

Loops say *how* to process data step by step. Streams say *what* you want: 'the names of paid orders over ₹1,000, sorted, as a list'. The result is often shorter and closer to the problem statement, and the same pipeline can even run in parallel.

Why it matters

Streams are used throughout modern Java code bases for reporting, data transformation and API responses.

Grouping and summarising data with collectors replaces many lines of manual map-building code.

Detailed explanation

Sources. collection.stream(), Arrays.stream(array), Stream.of(a, b, c), IntStream.range(0, n) / rangeClosed, Files.lines(path) and Stream.iterate/generate (with limit).

Intermediate operations return a new stream and are lazy — nothing happens until a terminal operation runs: filter, map, flatMap, distinct, sorted, limit, skip, peek, and mapToInt to switch to a primitive stream.

Terminal operations produce a result or side effect: toList() (Java 16), collect(...), forEach, count, sum/average (primitive streams), min/max, reduce, anyMatch/allMatch/noneMatch, findFirst.

Collectors. Collectors.groupingBy(classifier) (optionally with a downstream collector such as counting(), summingInt, averagingDouble or mapping), partitioningBy(predicate), toMap(keyFn, valueFn), joining(", ") and toSet().

Optional. Operations that might find nothing — findFirst, max, min — return Optional<T>. Use orElse, orElseGet, orElseThrow, ifPresent or map rather than calling get() blindly.

Rules. A stream can be consumed only once. Lambdas in a pipeline should not modify shared state or the source collection. Parallel streams (parallelStream()) can speed up large CPU-bound jobs but add overhead for small ones.

Syntax

Java
List<String> names = orders.stream()
.filter(o -> o.paid() && o.amount() > 1000) // keep some
.sorted(Comparator.comparing(Order::amount)) // order them
.map(Order::customer) // transform
.distinct()
.toList(); // terminal
Map<String, Long> perCity = people.stream()
.collect(Collectors.groupingBy(Person::city, Collectors.counting()));
int total = IntStream.rangeClosed(1, 100).sum();
  • Nothing runs until a terminal operation is called.
  • A stream can't be reused after its terminal operation.
  • toList() returns an unmodifiable list; use collect(Collectors.toList()) for a modifiable one.

Code examples

filter, map, sorted and friends

Java
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class Main {
public static void main(String[] args) {
List<Integer> nums = List.of(5, 12, 7, 3, 12, 20, 8, 1);
List<Integer> evensSquared = nums.stream().filter(n -> n % 2 == 0).map(n -> n * n).toList();
System.out.println(evensSquared);
System.out.println(nums.stream().distinct().sorted().toList());
System.out.println(nums.stream().sorted((a, b) -> b - a).limit(3).toList());
System.out.println("count > 6: " + nums.stream().filter(n -> n > 6).count() + ", any > 15: " + nums.stream().anyMatch(n -> n > 15));
System.out.println("sum 1..100 = " + IntStream.rangeClosed(1, 100).sum());
List<String> words = List.of("stream", "lambda", "java", "list");
System.out.println(words.stream().filter(w -> w.length() > 4).map(String::toUpperCase).collect(Collectors.joining(", ", "[", "]")));
}
}
Output
[144, 144, 400, 64]
[1, 3, 5, 7, 8, 12, 20]
[20, 12, 12]
count > 6: 5, any > 15: true
sum 1..100 = 5050
[STREAM, LAMBDA]

Reduce, statistics and Optional

Java
import java.util.*;
import java.util.stream.*;
public class Main {
public static void main(String[] args) {
List<Integer> marks = List.of(72, 95, 58, 81, 66);
int total = marks.stream().reduce(0, Integer::sum);
IntSummaryStatistics stats = marks.stream().mapToInt(Integer::intValue).summaryStatistics();
System.out.println("total " + total + ", min " + stats.getMin() + ", max " + stats.getMax() + ", avg " + stats.getAverage());
Optional<Integer> firstAbove90 = marks.stream().filter(m -> m > 90).findFirst();
Optional<Integer> firstAbove99 = marks.stream().filter(m -> m > 99).findFirst();
System.out.println(firstAbove90.orElse(-1) + " " + firstAbove99.orElse(-1) + " " + firstAbove99.isPresent());
firstAbove90.ifPresent(m -> System.out.println("topper scored " + m));
System.out.println(Stream.iterate(1, x -> x * 2).limit(10).map(String::valueOf).collect(Collectors.joining(" ")));
}
}
Output
total 372, min 58, max 95, avg 74.4
95 -1 false
topper scored 95
1 2 4 8 16 32 64 128 256 512

More examples

Grouping and reporting with collectors

Java
import java.util.*;
import java.util.stream.*;
public class Main {
record Sale(String region, String product, int units, double price) {
double revenue() { return units * price; }
}
public static void main(String[] args) {
List<Sale> sales = List.of(
new Sale("North", "Laptop", 3, 55000), new Sale("South", "Mouse", 40, 600),
new Sale("North", "Mouse", 25, 600), new Sale("East", "Laptop", 2, 52000),
new Sale("South", "Desk", 5, 7500), new Sale("East", "Mouse", 10, 650));
Map<String, Double> byRegion = sales.stream()
.collect(Collectors.groupingBy(Sale::region, TreeMap::new, Collectors.summingDouble(Sale::revenue)));
System.out.println("revenue by region: " + byRegion);
Map<String, Integer> unitsByProduct = sales.stream()
.collect(Collectors.groupingBy(Sale::product, TreeMap::new, Collectors.summingInt(Sale::units)));
System.out.println("units by product: " + unitsByProduct);
Map<Boolean, List<String>> bigSmall = sales.stream()
.collect(Collectors.partitioningBy(s -> s.revenue() >= 50000, Collectors.mapping(s -> s.region() + "/" + s.product(), Collectors.toList())));
System.out.println("big: " + bigSmall.get(true) + " small: " + bigSmall.get(false));
String best = sales.stream().max(Comparator.comparingDouble(Sale::revenue)).map(s -> s.product() + " in " + s.region()).orElse("none");
System.out.println("biggest sale: " + best);
List<String> regionsByRevenue = byRegion.entrySet().stream()
.sorted(Map.Entry.<String, Double>comparingByValue().reversed())
.map(Map.Entry::getKey).toList();
System.out.println("ranking: " + regionsByRevenue);
List<List<String>> tags = List.of(List.of("java", "oop"), List.of("java", "streams"), List.of("sql"));
System.out.println("all tags: " + tags.stream().flatMap(List::stream).distinct().sorted().toList());
}
}
Output
revenue by region: {East=110500.0, North=180000.0, South=61500.0}
units by product: {Desk=5, Laptop=5, Mouse=75}
big: [North/Laptop, East/Laptop] small: [South/Mouse, North/Mouse, South/Desk, East/Mouse]
biggest sale: Laptop in North
ranking: [North, East, South]
all tags: [java, oop, sql, streams]

Step-by-step explanation

  • groupingBy(Sale::region, TreeMap::new, summingDouble(Sale::revenue)) groups sales by region into a sorted TreeMap and sums each group's revenue.
  • A second grouping totals units per product with summingInt.
  • partitioningBy splits the data into two groups (true/false); the downstream mapping collector turns each sale into a label.
  • max(...) returns an Optional, which map transforms and orElse unwraps safely.
  • Streaming over a map's entrySet() and sorting by value ranks the regions; flatMap flattens nested lists into one stream of tags.

Expected output

Running “Grouping and reporting with collectors” prints exactly:

TextOutput
revenue by region: {East=110500.0, North=180000.0, South=61500.0}
units by product: {Desk=5, Laptop=5, Mouse=75}
big: [North/Laptop, East/Laptop] small: [South/Mouse, North/Mouse, South/Desk, East/Mouse]
biggest sale: Laptop in North
ranking: [North, East, South]
all tags: [java, oop, sql, streams]

Practical applications

  • Building API responses from database results
  • Reports and dashboards: totals, averages and top-N lists
  • Data cleaning: filtering, de-duplicating and normalising records
  • Processing log files line by line with Files.lines

Best practices

  • Keep pipelines readable: one operation per line.
  • Prefer collectors over manual map building.
  • Use loops when they are clearer, for example with early exits or complex state.

Common mistakes

Reusing a stream

Avoid

Stream<String> s = names.stream();
long n = s.count();
List<String> l = s.toList(); // IllegalStateException

Prefer

long n = names.stream().count();
List<String> l = names.stream().toList();

A stream can be consumed only once; create a new one from the source for each pipeline.

Side effects inside the pipeline

Avoid

List<Integer> out = new ArrayList<>();
nums.stream().filter(n -> n > 0).forEach(out::add);

Prefer

List<Integer> out = nums.stream().filter(n -> n > 0).toList();

Mutating external state from a stream is error-prone (and unsafe in parallel); let a terminal operation build the result.

Important notes

  • Stream.toList() was added in Java 16; on older versions use collect(Collectors.toList()).
  • groupingBy uses a HashMap by default; pass TreeMap::new (as above) when you need sorted, predictable output.

Key takeaways

  • A stream pipeline is a source, lazy intermediate operations and one terminal operation.
  • Collectors group, count, sum, partition and join data.
  • Operations that may find nothing return Optional; unwrap it with orElse or ifPresent.

Try it yourself

  1. 1
    From a list of students, find the average marks per branch, sorted by branch.
  2. 2
    Find the three most frequent words in a paragraph using streams.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

9 questions test this exact topic. Answers and explanations are revealed after you submit.

  • BeginnerWhat is printed?
  • ModerateWhat is printed?
  • ModerateWhat is printed?
Practise this topic