■ JAVA STREAM API — COMPLETE NOTES ■
■ INTRODUCTION
■ What is Stream API?
- Introduced in Java 8.
- Used to process collections in a functional way.
- Focuses on “what to do” not “how to do it”.
- Doesn’t modify original data structure.
■ Think of a stream as a pipeline through which data flows — intermediate ops + terminal ops.
■ STREAM CREATION
• From Collections → list.stream()
• From Arrays → Arrays.stream(arr)
• Using Stream.of() → Stream.of(1,2,3)
• Using generate()/iterate() → Stream.generate(() -> 1).limit(5)
■ STREAM OPERATIONS OVERVIEW
Intermediate: map(), filter(), sorted(), distinct()
Terminal: collect(), forEach(), reduce(), count()
Example:
list.stream().filter(n -> n%2==0).map(n -> n*n).collect(Collectors.toList());
■ INTERMEDIATE OPERATIONS
filter() → filters elements
map() → transforms each element
flatMap() → flattens nested structures
sorted() → sorts elements
distinct() → removes duplicates
limit(n) → takes first n elements
skip(n) → skips first n elements
■ TERMINAL OPERATIONS
forEach() → applies action
collect() → gathers result
toArray(), count(), findFirst(), findAny()
allMatch(), anyMatch(), noneMatch()
reduce() → combines elements into one
■ STREAM COLLECTORS
toList(), toSet(), toMap(), joining(), counting()
summingInt(), groupingBy(), partitioningBy()
■ STREAM WITH CUSTOM CLASS
List s = ...
s.stream().filter(x->x.getMarks()>70)
.map(Student::getName).collect(Collectors.toList());
■ STREAMS WITH MAPS
map.entrySet().stream().filter(e->e.getValue()>1)
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
■ PARALLEL STREAMS
list.parallelStream().forEach(System.out::println);
Use for large data and independent tasks.
■ SHORT-CIRCUITING OPERATIONS
findFirst(), findAny(), anyMatch(), allMatch(), noneMatch(), limit()
■ ADVANCED EXAMPLES
Sort by marks: students.stream().sorted(Comparator.comparing(Student::getMarks))
Max marks: students.stream().max(Comparator.comparing(Student::getMarks))
Join list: list.stream().map(String::valueOf).collect(Collectors.joining(", "));
■ CHARACTERISTICS
Non-mutating, Lazy Evaluation, Not reusable, Sequential or Parallel
■ INTERVIEW QUESTIONS
Q1. map vs flatMap? → map: one-to-one, flatMap: one-to-many
Q2. Streams lazy? → Yes, until terminal op.
Q3. Can stream reuse? → No.
Q4. Collection vs Stream → Storage vs Processing.
■ COMPLETE METHOD LIST
Intermediate → filter(), map(), flatMap(), distinct(), sorted(), peek(), limit(), skip()
Terminal → forEach(), toArray(), reduce(), collect(), min(), max(), count(), findFirst(), findAny(),
anyMatch(), allMatch(), noneMatch()
■ SUMMARY TABLE
Create → stream(), of(), generate(), iterate()
Intermediate → filter(), map(), sorted(), distinct(), limit(), skip()
Terminal → collect(), reduce(), count(), forEach(), anyMatch()
Collector → toList(), joining(), groupingBy(), partitioningBy()