Stream (Stream API)
A Stream is a declarative, composable pipeline for processing a sequence of elements. Introduced in Java 8, streams let you express data transformations as a chain of operations (filter, map, reduce, collect) instead of explicit loops.
Example pipeline
List<String> names = List.of("Ada", "Grace", "Linus", "Ken");
long count = names.stream()
.filter(name -> name.length() > 3)
.map(String::toUpperCase)
.count();
// count = 2 ("GRACE" and "LINUS")
Stream vs collection
A collection stores data; a stream describes a computation. Streams are:
- Lazy β intermediate operations (
filter,map) only execute when a terminal operation (collect,count,forEach) runs. - One-shot β a stream can be consumed once. Re-running requires creating a new stream.
- Possibly parallel β
list.parallelStream()splits the work across the common ForkJoinPool.
Common operations
stream.filter(pred) // keep matching
.map(fn) // transform each element
.flatMap(fn) // map and flatten
.distinct() // remove duplicates
.sorted(comparator) // sort
.limit(n) // take first n
.skip(n) // drop first n
.reduce(identity, op) // fold to a single value
.collect(Collectors.toList()) // materialise as collection
Streams != java.io.InputStream
Note the naming clash: java.util.stream.Stream (this topic) is unrelated to java.io.InputStream (byte-level I/O). Always say "Stream API" or "java.util.stream" to disambiguate in conversation.