CKTIS / Java
Java Stream pipelines
Java Stream pipelines: A Stream is a single-use lazy pipeline of a source, intermediate operations, and a terminal operation; elements flow only when the terminal requests a result.
Version: Java SE 21 (JLS and Java SE API); examples verified on the repository Java runtime
Syntax
streamsA Stream is a single-use lazy pipeline of a source, intermediate operations, and a terminal operation; elements flow only when the terminal requests a result.
Use map, filter, and collectors for declarative aggregation, and close I/O-backed streams with try-with-resources.
Pipeline functions should be stateless and non-interfering; side effects may be elided, and parallel does not guarantee a speedup.
Reusing a stream can throw IllegalStateException, while an infinite stream needs limit or a short-circuiting operation for the terminal to finish.
limit bounds infinite iterate to 1..6, filter keeps 2,4,6, and map squares them; toList prints [4, 16, 36].
Examples
import java.util.List;
import java.util.stream.Stream;
public class Main {
public static void main(String[] args) {
List<Integer> squares = Stream.iterate(1, n -> n + 1)
.limit(6)
.filter(n -> n % 2 == 0)
.map(n -> n * n)
.toList();
System.out.println(squares);
}
}
Result
[4, 16, 36]
limit bounds infinite iterate to 1..6, filter keeps 2,4,6, and map squares them; toList prints [4, 16, 36].