Java Streams
A stream is a flow of values taken from a source for processing. A pipeline chains steps that keep, change and use each value in order.
A filter, map and forEach pipeline
The pipeline keeps the passing scores first. map then turns each score into a labelled line for printing.
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Integer> scores = List.of(45, 82, 61, 90);
scores.stream()
.filter(score -> score >= 60)
.map(score -> "pass " + score)
.forEach(System.out::println);
}
}The source list prints unchanged
The same pipeline prints the passing scores. The list itself then prints with every original value still inside.
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Integer> scores = List.of(45, 82, 61, 90);
scores.stream()
.filter(score -> score >= 60)
.forEach(System.out::println);
System.out.println(scores);
}
}count ends a pipeline with a number
The filter keeps the names that start with A. count answers how many values reached the end.
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> names = List.of("Ana", "Ben", "Alba", "Cy");
long count = names.stream()
.filter(name -> name.startsWith("A"))
.count();
System.out.println(count);
}
}Example
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> words = List.of("go", "java", "stream", "code");
words.stream()
.filter(word -> word.length() >= 4)
.map(String::toUpperCase)
.forEach(System.out::println);
long count = words.stream()
.filter(word -> word.length() >= 4)
.count();
System.out.println(count);
}
}Key points
- filter keeps only the values whose test answers true.
- map converts each value that reaches it into a new value.
- forEach ends a pipeline by running an action on each value left.
- count ends a pipeline with the number of values left.
- A stream pipeline runs once and cannot be reused.
- A pipeline reads its source and leaves the source unchanged.
In this example, the first pipeline keeps the words with four or more letters and prints them in capitals. A second pipeline over the same list counts those words. The list supplies both pipelines and stays unchanged.
Note
A stream is a processing flow over data, and the data itself stays in its collection.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Which stream step converts each value into a new value?