Core Stream Operations
Intermediate operations transform a stream into another stream. They are lazy and do not execute until a terminal operation is invoked.
Filtering
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
List<Integer> evenNumbers = numbers.stream()
.filter(n -> n % 2 == 0)
.collect(Collectors.toList());
Mapping
List<String> names = Arrays.asList("alice", "bob", "charlie");
List<String> upperNames = names.stream()
.map(String::toUpperCase)
.collect(Collectors.toList());
graph TD
A[Intermediate Operations] --> B[filter]
A --> C[map]
A --> D[flatMap]
A --> E[distinct]
A --> F[sorted]
A --> G[peek]
A --> H[limit]
A --> I[skip]
Terminal Operations
Terminal operations produce a result or side-effect and close the stream.
Operation |
Description |
Return Type |
collect |
Collect stream elements |
Collection |
forEach |
Perform action on each element |
void |
reduce |
Reduce stream to single value |
Optional/value |
count |
Count stream elements |
long |
anyMatch |
Check if any element matches |
boolean |
allMatch |
Check if all elements match |
boolean |
findFirst |
Return first element |
Optional |
findAny |
Return any element |
Optional |
Reduction Example
int sum = numbers.stream()
.reduce(0, (a, b) -> a + b);
Advanced Stream Techniques
Grouping and Partitioning
Map<Boolean, List<Integer>> partitioned = numbers.stream()
.collect(Collectors.partitioningBy(n -> n % 2 == 0));
Map<Integer, List<String>> grouped = names.stream()
.collect(Collectors.groupingBy(String::length));
Parallel Streams
long count = numbers.parallelStream()
.filter(n -> n > 5)
.count();
LabEx Learning Tip
LabEx provides interactive environments to practice and master these stream operations, helping you develop robust Java programming skills.