📖 Stream: a pipeline that processes the elements of a collection. It has a source, any number of intermediate operations (lazy) and one terminal operation. A stream does not change the original collection.
Source (List)→filter()→map()→sorted()→reduce() / collect()
Intermediate operations (filter, map, sorted) build the pipeline. A terminal operation (reduce, collect, forEach) starts it.
| Operation | Takes | Does | Result type |
|---|
| filter() | Predicate | Keeps the elements that pass the test | Stream (fewer or equal elements) |
| map() | Function | Transforms every element | Stream (same count, new values) |
| reduce() | BinaryOperator | Combines all elements into one value | Single value |
| sorted() | Comparator (optional) | Sorts | Stream |
| collect() | Collector | Gathers the result into a List, Set … | Collection |
| forEach(), count(), distinct(), limit() | | Other common operations | |
1 2 3 4 5 6→filter: even→2 4 6→map: square→4 16 36→reduce: sum→56
import java.util.*;
import java.util.stream.*;
public class StreamDemo {
public static void main(String[] args) {
List<Integer> nums = List.of(1, 2, 3, 4, 5, 6);
System.out.println("filter (even) : " + nums.stream().filter(n -> n % 2 == 0).collect(Collectors.toList()));
System.out.println("map (square) : " + nums.stream().map(n -> n * n).collect(Collectors.toList()));
System.out.println("reduce (sum) : " + nums.stream().reduce(0, (a, b) -> a + b));
int result = nums.stream()
.filter(n -> n % 2 == 0) // keep 2, 4, 6
.map(n -> n * n) // 4, 16, 36
.reduce(0, Integer::sum); // 56
System.out.println("sum of squares of even numbers = " + result);
List<String> names = Arrays.asList("Raj", "Amit", "Neha", "Karan");
System.out.println("sorted by length, then name: " + names.stream()
.sorted(Comparator.comparing(String::length).thenComparing(Comparator.naturalOrder()))
.collect(Collectors.toList()));
System.out.println("names starting with A or N : " + names.stream()
.filter(s -> s.startsWith("A") || s.startsWith("N"))
.map(String::toUpperCase)
.collect(Collectors.toList()));
}
}
// Output
filter (even) : [2, 4, 6]
map (square) : [1, 4, 9, 16, 25, 36]
reduce (sum) : 21
sum of squares of even numbers = 56
sorted by length, then name: [Raj, Amit, Neha, Karan]
names starting with A or N : [AMIT, NEHA]
Sorting: a plain list can be sorted with list.sort(comparator) or Collections.sort(list). In a stream use sorted() or sorted(Comparator.comparing(...).thenComparing(...)).