Sub topic 5
Selecting and Transforming Elements with filter and map
Most stream work comes down to two jobs. You pick the elements you want, and you change them into something else. The filter and map operations handle these two jobs. Both are intermediate operations. An intermediate operation is a step that takes a stream and gives back a new stream, so you can chain more steps after it.
filter: Keep Only What Matches
filter keeps the elements that pass a test and drops the rest. The test is a predicate. A predicate is a function that takes one element and returns true or false.
For example, name -> name.length() > 3 is a predicate. It returns true for "alice" and false for "bob".
map: Change Each Element
map takes every element and turns it into a new value. You give it a function that receives one element and returns the new one. The stream keeps the same number of elements, but each one has been changed.
You can pass a lambda such as s -> s.toUpperCase(). You can also pass the shorter method reference String::toUpperCase. Both do the same thing.
A Worked Example
This program keeps names longer than three characters and turns them into upper case.
import java.util.List;
import java.util.stream.Collectors;
public class FilterMapExample {
public static void main(String[] args) {
List<String> names = List.of("alice", "bob", "carol", "dave");
List<String> result = names.stream()
.filter(name -> name.length() > 3)
.map(String::toUpperCase)
.collect(Collectors.toList());
System.out.println(result); // [ALICE, CAROL, DAVE]
}
}Here is what happens to each name:
| Name | Passes filter? | After map |
|---|---|---|
| alice | yes | ALICE |
| bob | no | (dropped) |
| carol | yes | CAROL |
| dave | yes | DAVE |
map Can Change the Type
map does not have to return the same type. Here, strings become integers:
import java.util.List;
import java.util.stream.Collectors;
public class MapTypeExample {
public static void main(String[] args) {
List<String> words = List.of("sun", "moon", "star");
List<Integer> lengths = words.stream()
.map(String::length)
.collect(Collectors.toList());
System.out.println(lengths); // [3, 4, 4]
}
}The stream started as a stream of String and ended as a stream of Integer.
Exercises
Exercise
Given List.of(1, 2, 3, 4, 5, 6), write a pipeline that keeps only even numbers and multiplies each by 10, collecting the result into a list. What does it print?
Show answer
numbers.stream().filter(n -> n % 2 == 0).map(n -> n * 10).collect(Collectors.toList()) prints [20, 40, 60].
Exercise
Does map ever change how many elements are in a stream? Does filter?
Show answer
map never changes the count, because every element becomes exactly one new element. filter can lower the count, because it drops elements that fail the test.