← All lessons
Advanced Java · Lesson 2 of 9

Streams and Optional

A stream is a pipeline that data flows through: start from a collection, pass the items through steps (keep some, change each, sort them) and finish by collecting a result. It says what you want rather than how to loop for it.

Java
List<String> names = List.of("ana", "Ben", "cyrus", "dee", "Eleanor");
List<String> result = names.stream()
    .filter(n -> n.length() <= 5)
    .map(n -> n.substring(0, 1).toUpperCase() + n.substring(1).toLowerCase())
    .sorted()
    .toList();
System.out.println(result);
Prints
[Ana, Ben, Cyrus, Dee]

The steps in the middle (filter, map, sorted, distinct, limit, skip) are intermediate operations: each gives back a new stream. The pipeline does nothing until a terminal operation (toList, count, forEach, collect, reduce, findFirst, anyMatch) asks for a result. Streams are lazy and single use: run the terminal step once and that stream is finished; make a new one from the list to go again.

Numbers

mapToInt turns a stream into an IntStream with number helpers like sum, average and max. IntStream.range(a, b) counts from a up to b, a stream version of the counting loop.

Java
record Order(String customer, int cents) {}
List<Order> orders = List.of(new Order("ana", 1250), new Order("ben", 800), new Order("ana", 300), new Order("cy", 4000));
int total = orders.stream().mapToInt(Order::cents).sum();
System.out.println(total);
System.out.println(orders.stream().filter(o -> o.cents() > 1000).count());
System.out.println(orders.stream().anyMatch(o -> o.customer().equals("cy")));
System.out.println(IntStream.rangeClosed(1, 5).map(i -> i * i).boxed().toList());
System.out.println(Stream.of(3, 4, 5).reduce(1, (a, b) -> a * b));
Prints
6350
2
true
[1, 4, 9, 16, 25]
60

reduce(start, combine) folds the items into one value: here 1 × 3 × 4 × 5. (record works inside a method too, as a local type, which these examples use to stay short.)

Collectors

collect with a Collector builds richer results. groupingBy is the stream version of the counting map from the last course: it sorts items into groups by a key.

Java
record Order(String customer, int cents) {}
List<Order> orders = List.of(new Order("ana", 1250), new Order("ben", 800), new Order("ana", 300), new Order("cy", 4000));
Map<String, Integer> byCustomer = orders.stream()
    .collect(Collectors.groupingBy(Order::customer, TreeMap::new, Collectors.summingInt(Order::cents)));
System.out.println(byCustomer);
Map<Boolean, Long> bigOrSmall = orders.stream()
    .collect(Collectors.partitioningBy(o -> o.cents() >= 1000, Collectors.counting()));
System.out.println(bigOrSmall);
String who = orders.stream().map(Order::customer).distinct().collect(Collectors.joining(", ", "<", ">"));
System.out.println(who);
Prints
{ana=1550, ben=800, cy=4000}
{false=2, true=2}
<ana, ben, cy>

Optional

Some answers might not exist: the first order over $100, the oldest member of an empty club. Rather than return null and hope the caller checks, stream steps like findFirst, max and min return an Optional: a box that holds a value or is empty. It makes "maybe missing" part of the type, and its methods handle both cases.

Java
List<Integer> scores = List.of(42, 77, 91, 63);
Optional<Integer> firstHigh = scores.stream().filter(s -> s > 90).findFirst();
Optional<Integer> firstHuge = scores.stream().filter(s -> s > 100).findFirst();
System.out.println(firstHigh.isPresent() + " " + firstHigh.get());
System.out.println(firstHuge.isEmpty());
System.out.println(firstHuge.orElse(0));
System.out.println(firstHigh.map(s -> "top score " + s).orElse("none"));
firstHuge.ifPresentOrElse(s -> System.out.println("found " + s), () -> System.out.println("nobody over 100"));
Prints
true 91
true
0
top score 91
nobody over 100

orElse gives a fallback, map changes the value if there is one, ifPresent runs code only when there is one, and orElseThrow() throws when it's empty. Calling get() on an empty Optional throws, so prefer the others.

Streams aren't always better than loops. Use one when the job is a clear pipeline (filter, transform, collect). A loop is often clearer when there's lots of state, early exits or side effects.

Practice

What does this print?

System.out.println(Stream.of(1, 2, 3, 4, 5, 6).filter(n -> n % 2 == 0).map(n -> n * 10).toList());
More info

Quick reference

xs.stream()Start a pipeline from a collection.
filter / map / sorted / distinct / limitIntermediate steps; each returns a stream.
toList / count / forEach / reduce / collectTerminal steps; they run the pipeline.
mapToInt(...).sum() / average()Number streams with maths helpers.
IntStream.range(a, b)a up to, not including, b.
Collectors.groupingBy / partitioningBy / joiningGroup by a key / split true-false / join text.
Optional: orElse / map / ifPresent / orElseThrowA value that may be missing.

Related courses