Java Stream API & Collectors —
Complete Guide (Java 17+)
This guide covers every important method of Java Stream API and Collectors with examples,
explanations, and corner cases. Commonly used methods are marked with ★.
1) Stream Model & Lifecycle
• Stream is lazy and one-time use
• Intermediate ops vs terminal ops
• Parallel streams need caution
2) Creating Streams
• Stream.of(), empty(), builder()
• Arrays.stream(), Collection.stream()
• Stream.iterate(), generate()
• Files.lines(), Pattern.splitAsStream()
• Stream.concat()
Stream<Integer> s = Stream.iterate(1, n -> n + 1).limit(5);
s.forEach(System.out::println);
3) Intermediate Operations
★ filter, map, flatMap, distinct, sorted, limit, skip, peek, takeWhile, dropWhile
List<Integer> lengths = List.of("hi","stream","api").stream()
.filter(w -> w.length() > 2)
.map(String::length)
.toList();
4) Terminal Operations
★ forEach, collect, toList, reduce, count, min, max, anyMatch, allMatch, findFirst, findAny
var list = List.of(1,2,3);
var a = list.stream().toList(); // unmodifiable
var b = list.stream().collect(Collectors.toList()); // mutable
5) Primitive Streams
★ IntStream.range, rangeClosed, sum, average, summaryStatistics, boxed()
6) Collectors
★ toList, toSet, toMap, groupingBy, partitioningBy, counting, joining, summingInt, teeing
Map<Character, Long> counts = List.of("Dog","dove","Cat").stream()
.collect(Collectors.groupingBy(s ->
Character.toLowerCase(s.charAt(0)),
Collectors.counting()));
7) Corner Cases & Tips
• Stream reuse throws IllegalStateException
• distinct needs equals/hashCode
• toMap duplicate keys => IllegalStateException
• Always close IO streams
• peek only for debugging
8) Cheat Sheet
★ map, filter, collect(toList), groupingBy, toMap(mergeFn), summaryStatistics, joining