What actually changes when you move from a collection to a stream in Java?
Three things change, and the biggest one is that the data is no longer the thing that you are working with.
A collection holds data. It has the values in it, you can look at them, you can change them, and you can walk through them as many times as you like. A stream describes a calculation. It does not hold the values, it does not copy them, and it can be used once.
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
List<String> names = List.of("Ada", "Grace", "Alan", "Katherine");
// The collection version holds the results as it goes.
List<String> longNames = new ArrayList<String>();
for (String name : names) {
if (name.length() > 4) {
longNames.add(name.toUpperCase());
}
}
// The stream version describes the calculation.
List<String> same = names.stream()
.filter(name -> name.length() > 4)
.map(name -> name.toUpperCase())
.collect(Collectors.toList());
System.out.println("the collection : " + longNames);
System.out.println("the stream : " + same);
// The collection can be walked through again and again.
System.out.println("count : " + names.stream().count());
System.out.println("count : " + names.stream().count());
}
}
So the three changes are these.
The first one is that the data is not copied. A stream over a list of a million items does not make a second list of a million items. It just says "take these values from that list". That matters when the collection is large.
The second one is that the work is lazy. Building the pipeline does not do anything. The work only happens when you ask for the result.
The third one is that a stream can only be used once, while a collection can be walked through as many times as you like.
There is one more change that is easy to miss. The pipeline describes a plan, and the runtime is free to carry it out in a better way than you would have written. That is why the stream version is often faster than the loop even though it does more work behind the scenes.
The next question in this topic looks at the lazy part in detail.