Sub topic 13
A First Look at Lambdas in Streams
In the last few chapters you used lambdas with list methods like removeIf and replaceAll. You also combined small functions with andThen and Predicate.and. Streams bring these ideas together. With a stream you can describe a whole chain of work on a collection, one step at a time, and give each step a lambda.
This chapter only introduces streams. It focuses on how lambdas and method references fit into them, so it does not cover every stream feature.
What Is a Stream?
A stream is a sequence of values that you process one step after another. It comes from the java.util.stream package. A stream does not store data the way a list does. It reads values from a source, such as a List, and passes each value through the steps you ask for.
A stream pipeline is the full chain of steps. Every pipeline has three parts:
- A source: where the values come from. For a collection, you call
.stream(). - Zero or more intermediate operations: steps that turn a stream into another stream, such as
filterormap. - Exactly one terminal operation: the last step, which produces a result or a side effect, such as
collect,count, orforEach.
Your First Pipeline
Here is a list of names. We want the names longer than two letters, in upper case, sorted.
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class FirstStream {
public static void main(String[] args) {
List<String> names = Arrays.asList("Ann", "bob", "Cy", "dave", "Dora");
List<String> result = names.stream()
.filter(n -> n.length() > 2) // keep names longer than 2
.map(String::toUpperCase) // change each name
.sorted() // natural (alphabetical) order
.collect(Collectors.toList()); // gather into a new List
System.out.println(result); // [ANN, BOB, DAVE, DORA]
System.out.println(names); // [Ann, bob, Cy, dave, Dora]
}
}Each line does one job:
filterkeeps only the values for which the lambda returnstrue. "Cy" is dropped.mapchanges each value into a new value. Here, the method referenceString::toUpperCasechanges each name to upper case.sortedputs the values in order.collect(Collectors.toList())gathers the results into a new list.
The original names list did not change. A stream reads from its source but does not modify it. removeIf and replaceAll from the Collections chapter work differently, because they change the list itself.
The Same Work with a Loop
For comparison, here is the loop version:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class LoopVersion {
public static void main(String[] args) {
List<String> names = Arrays.asList("Ann", "bob", "Cy", "dave", "Dora");
List<String> result = new ArrayList<>();
for (String n : names) {
if (n.length() > 2) {
result.add(n.toUpperCase());
}
}
Collections.sort(result);
System.out.println(result); // [ANN, BOB, DAVE, DORA]
}
}Both versions work. In the stream version, each step has a name that says what it does, so you don't have to work out how the loop does it. The loop version is still fine, and sometimes it is clearer. You don't have to replace every loop with a stream.
Every Step Takes a Functional Interface
Stream methods take the same interfaces you learned in java.util.function. That is why lambdas and method references fit into them.
| Stream method | Kind | Parameter type | Example lambda |
|---|---|---|---|
| `filter` | intermediate | `Predicate<T>` | `n -> n > 0` |
| `map` | intermediate | `Function<T, R>` | `s -> s.length()` |
| `sorted` | intermediate | `Comparator<T>` (optional) | `(a, b) -> a.compareTo(b)` |
| `forEach` | terminal | `Consumer<T>` | `s -> System.out.println(s)` |
| `anyMatch` | terminal | `Predicate<T>` | `n -> n > 7` |
| `reduce` | terminal | `BinaryOperator<T>` | `(a, b) -> a + b` |
| `count` | terminal | none |
When you write .filter(n -> n.length() > 2), the compiler sees that filter wants a Predicate<String>. It uses that target type to work out that n is a String and the lambda must return a boolean. This is the target typing you met earlier.
More Terminal Operations
The terminal operation decides what you get at the end. Here are a few common ones on a list of numbers:
import java.util.Arrays;
import java.util.List;
public class NumberStreams {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(4, 7, 1, 8, 3, 6);
long oddCount = numbers.stream()
.filter(n -> n % 2 != 0)
.count();
System.out.println(oddCount); // 3
boolean anyBig = numbers.stream()
.anyMatch(n -> n > 7);
System.out.println(anyBig); // true
int total = numbers.stream()
.reduce(0, Integer::sum);
System.out.println(total); // 29
int sumOfEvenSquares = numbers.stream()
.filter(n -> n % 2 == 0)
.mapToInt(n -> n * n)
.sum();
System.out.println(sumOfEvenSquares); // 16 + 64 + 36 = 116
numbers.stream()
.map(n -> "Number " + n)
.forEach(System.out::println);
}
}The reduce and mapToInt steps need a closer look:
reduce(0, Integer::sum)starts at0and combines values two at a time.Integer::sumis a static method reference that fitsBinaryOperator<Integer>.mapToIntturns the stream into anIntStream, which is a stream of plainintvalues. It accepts aToIntFunction, one of the primitive interfaces from the previous chapter. AnIntStreamhas handy methods likesum()and avoids boxing.
Streams Are Lazy
Lazy means the work is not done until it is needed. Intermediate operations do nothing by themselves. They only record what to do. The work starts when the terminal operation runs.
You can see this by printing from inside a lambda:
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;
public class LazyDemo {
public static void main(String[] args) {
List<String> names = Arrays.asList("Ann", "bob", "Cy");
Stream<String> longNames = names.stream()
.filter(n -> {
System.out.println("checking " + n);
return n.length() > 2;
});
System.out.println("Nothing checked yet");
long count = longNames.count(); // the filter runs now
System.out.println(count);
}
}The output is:
Nothing checked yet
checking Ann
checking bob
checking Cy
2The filter lambda ran only when count() was called.
A Stream Can Be Used Only Once
After a terminal operation runs, the stream is used up. Calling another operation on it throws an IllegalStateException.
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;
public class ReuseDemo {
public static void main(String[] args) {
List<String> names = Arrays.asList("Ann", "bob", "Cy");
Stream<String> s = names.stream();
System.out.println(s.count()); // 3
try {
s.count(); // the stream is already used
} catch (IllegalStateException e) {
System.out.println("Error: " + e.getMessage());
}
}
}The fix is simple: call names.stream() again to get a fresh stream each time you need one.
Keep Stream Lambdas Simple and Side-Effect Free
A side effect is a change a lambda makes to something outside itself, like adding to a list declared elsewhere. The effectively-final rule already stops you from reassigning a local variable inside a lambda. But you can still change an object that the variable points to, and inside a stream that is usually a mistake:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class SideEffects {
public static void main(String[] args) {
List<String> names = Arrays.asList("Ann", "bob", "Cy");
// Avoid: the lambda changes an outside list
List<String> bad = new ArrayList<>();
names.stream().filter(n -> n.length() > 2).forEach(n -> bad.add(n));
// Prefer: let collect build the list
List<String> good = names.stream()
.filter(n -> n.length() > 2)
.collect(Collectors.toList());
System.out.println(bad); // [Ann, bob]
System.out.println(good); // [Ann, bob]
}
}Both print the same thing here. The collect version is clearer, and it stays correct if you later switch to a parallel stream, which runs steps on several threads at once. Use forEach for output, like printing. Use collect to build results.
Common Mistakes
| Mistake | What happens | Fix |
|---|---|---|
| No terminal operation | Nothing runs | End with `collect`, `count`, `forEach`, and so on |
| Reusing a stream | `IllegalStateException` | Call `.stream()` again |
| Expecting the source list to change | The list stays the same | Use the collected result, or use `replaceAll` or `removeIf` |
| Adding to an outside list in `forEach` | Works, but fragile | Use `collect` |
| `map` lambda that returns nothing | Compile error | `map` needs a `Function` that returns a value |
Exercise
Given List<String> words = Arrays.asList("tree", "sky", "river", "sun", "mountain"); write a stream pipeline that keeps words with more than 3 letters, maps each to its length, and collects the lengths into a List<Integer>. What does it print?
Show answer
List<Integer> lengths = words.stream().filter(w -> w.length() > 3).map(String::length).collect(Collectors.toList()); System.out.println(lengths); prints [4, 5, 8]. "sky" and "sun" are removed by filter, and map turns "tree", "river", and "mountain" into 4, 5, and 8.
Exercise
A programmer writes names.stream().filter(n -> n.startsWith("A")).map(String::toUpperCase); on its own line and is surprised that nothing seems to happen. Why, and how would you fix it?
Show answer
The pipeline has no terminal operation, and streams are lazy, so the filter and map lambdas never run. Add a terminal operation, for example .forEach(System.out::println) to print the results or .collect(Collectors.toList()) to keep them.
Exercise
Which functional interface does each step need in numbers.stream().filter(n -> n > 2).map(n -> n * 10).reduce(0, (a, b) -> a + b), where numbers is a List<Integer>? What is the result for the list [1, 2, 3, 4]?
Show answer
filter needs a Predicate<Integer>, map needs a Function<Integer, Integer>, and reduce needs a BinaryOperator<Integer>. Only 3 and 4 pass the filter, map turns them into 30 and 40, and reduce adds them starting from 0, so the result is 70.