Java Streams API Complete Guide
Ad
What is the Streams API?
Introduced in Java 8, the Streams API lets you process collections in a functional, declarative style — filter, map, reduce — without manual loops.
Basic Pipeline
List<Integer> nums = List.of(1, 2, 3, 4, 5, 6);
int sum = nums.stream()
.filter(n -> n % 2 == 0) // keep evens
.mapToInt(n -> n * 10) // transform
.sum(); // 2*10 + 4*10 + 6*10 = 120
Common Operations
| Operation | Does |
|---|---|
| filter | Keep matching elements |
| map | Transform each element |
| collect | Gather into a list/set/map |
| reduce | Combine into one value |
| sorted | Sort the stream |
Collecting Results
List<String> names = people.stream()
.filter(p -> p.getAge() > 18)
.map(Person::getName)
.collect(Collectors.toList());
FAQs
Are streams faster than loops?
Not necessarily — they prioritise readability. parallelStream() can speed up large datasets.
Can I reuse a stream?
No — a stream is consumed once. More in our Java guides.
