Sub topic 13
A First Look at Lambdas in Streams
You have used lambdas with list methods like removeIf and replaceAll. Those methods change the list itself. Streams give you a different way to work with a collection. You describe a series of steps, and Java runs your lambdas on each element as it passes through those steps.
What Is a Stream?
A stream is a sequence of elements that you can process one step at a time. It is not a collection, and it does not store data. It reads from a source, such as a List, and passes each element along a chain of steps.
A stream pipeline is the full chain. It has three parts:
- A source. You call
.stream()on a collection to start. - Intermediate operations. These are steps like
filterandmap. Each one returns a new stream, so you can chain them. - A terminal operation. This is the last step, like
collectorcount. It produces the final result and ends the stream.
Each Step Takes a Lambda
Most stream steps expect a functional interface you already know. That means you can pass a lambda or a method reference to them.
| Operation | What it does | Interface it expects |
|---|---|---|
| `filter` | Keeps elements that pass a test | `Predicate<T>` |
| `map` | Turns each element into another value | `Function<T, R>` |
| `forEach` | Does something with each element | `Consumer<T>` |
| `sorted` | Puts elements in order | `Comparator<T>` (optional) |
A Worked Example
This program keeps fruit names longer than four letters, makes them upper case, and sorts them.
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class FruitStream {
public static void main(String[] args) {
List<String> fruits = Arrays.asList("apple", "Banana", "cherry", "date", "Elderberry");
List<String> result = fruits.stream()
.filter(f -> f.length() > 4) // Predicate: keep long names
.map(String::toUpperCase) // Function: change each name
.sorted() // natural order
.collect(Collectors.toList()); // gather into a new List
System.out.println(result); // [APPLE, BANANA, CHERRY, ELDERBERRY]
System.out.println(fruits); // [apple, Banana, cherry, date, Elderberry]
long count = fruits.stream()
.filter(f -> f.startsWith("a"))
.count();
System.out.println(count); // 1
}
}Here is what happens step by step:
filter(f -> f.length() > 4)drops"date"because it has only four letters.map(String::toUpperCase)turns each remaining name into upper case. This is an unbound method reference.sorted()puts the names in alphabetical order.collect(Collectors.toList())gathers the results into a new list.
The second print shows that fruits is unchanged. A stream builds a new result. It does not change its source.
Streams vs. List Methods
| Goal | List method | Stream |
|---|---|---|
| Remove short names | `removeIf` changes the list | `filter` builds a new result |
| Change every name | `replaceAll` changes the list | `map` builds a new result |
Use list methods when you want to change the list in place. Use a stream when you want a new result and the original list should stay as it is.
Exercise
Given List<Integer> nums = Arrays.asList(3, 8, 5, 12, 7), write a stream pipeline that keeps only even numbers, multiplies each by 10, and collects them into a list. What does it print?
Show answer
List<Integer> out = nums.stream().filter(n -> n % 2 == 0).map(n -> n * 10).collect(Collectors.toList()); System.out.println(out); prints [80, 120]. filter uses a Predicate to keep 8 and 12, and map uses a Function to multiply each one by 10.
Exercise
A student writes names.stream().map(n -> { System.out.println(n); return n; }); and nothing is printed. Why?
Show answer
The pipeline has no terminal operation. Intermediate steps like map are lazy, so the lambda never runs. Adding a terminal operation such as .collect(Collectors.toList()) or .count() makes it run.