How do map, filter and reduce compose in a Java stream pipeline, and what does each stage do?
They are the three steps that almost every stream pipeline is built from, and each one does a different kind of work.
The step filter decides whether a value stays or goes. It takes one value and gives back either that value or nothing at all. It never changes the value itself.
The step map changes one value into one other value. It takes a value and gives back a value of a different type, or the same type with different contents.
The step reduce folds the whole stream into one value. It takes the values one at a time and combines them into a running result.
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
List<String> names = List.of("Ada", "Grace", "Alan", "Katherine");
// filter keeps some, map changes each one, reduce folds them together.
Optional<String> longest = names.stream()
.filter(name -> name.length() > 4)
.map(name -> name.toUpperCase())
.reduce((first, second) -> first.length() >= second.length() ? first : second);
System.out.println("the longest : " + longest.orElse("none"));
// The same pipeline, but collecting the answers into a list.
List<String> upper = names.stream()
.filter(name -> name.length() > 4)
.map(name -> name.toUpperCase())
.collect(Collectors.toList());
System.out.println("all of them : " + upper);
}
}
So they compose because they all take a stream and give back a stream of the same shape. You can put a filter after a map or a map after a filter, and the order that you write them in is the order that they run in.
The next question in this topic looks at the most common use of reduce, which is adding up.