Video in progress
What do filter() and map() do? Give a simple example of using them together.
filter drops the elements that don't match a condition, so the count can shrink. map converts each element into another value: the count stays the same, and the type can change.
📖 Answer
Say you need the emails of only the active users from a list of users:
record User(String email, boolean active) {}
List<String> emails = users.stream()
.filter(User::active) // Predicate<User>
.map(User::email) // Function<User, String>
.map(String::toLowerCase)
.toList();
After filter the element type is still User, only some elements drop out. After map the stream becomes a Stream<String>.
Order can matter. If you filter first, map runs on fewer elements. If map is an expensive operation (parsing, for example), putting the filter first helps.
One more tip: don't change anything outside inside map (adding to a list, writing to a log). Its job is only to transform the value.
Sign up to mark studied questions and save your progress.