What is the Stream API in Java, and what problem does it solve?
The Stream API is a way of describing a calculation over a set of values as a pipeline of steps.
Instead of a loop that collects results into a list, you write the steps in the order that they happen, and the library does the walking for you.
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> names = List.of("Ada", "Grace", "Alan", "Katherine");
// The loop version.
List<String> longNames = new java.util.ArrayList<String>();
for (String name : names) {
if (name.length() > 4) {
longNames.add(name.toUpperCase());
}
}
// The stream version.
List<String> same = names.stream()
.filter(name -> name.length() > 4)
.map(name -> name.toUpperCase())
.collect(java.util.stream.Collectors.toList());
System.out.println("the loop : " + longNames);
System.out.println("the stream : " + same);
}
}
So what problem does it solve? Three things.
The first one is that the code says what it means. The stream version reads as a list of steps, and you can see the filter and the change of case without holding the whole loop in your head.
The second one is that the steps can be joined together. Because each step gives back a stream of the same shape, you can add another step without changing anything else.
The third one is that the library can do the work more cheaply. The steps do not run one at a time through your code, they are joined into a single operation, and the runtime can optimise the whole thing. It can also spread the work over several threads when you ask it to.
The next question in this topic looks at how to make a stream and how to use it.