|
|
Stream filter(), map() and reduce()
Author: Venkata Sudhakar
Java 8 Streams provide a functional approach to processing collections. The three most commonly used operations are filter() for selecting elements, map() for transforming elements, and reduce() for aggregating elements into a single result. Operation Overview: 1. filter(Predicate) - Keeps only elements matching the predicate. 2. map(Function) - Transforms each element using the function. 3. reduce(identity, BinaryOperator) - Combines all elements into a single result. The below example shows how to use filter, map and reduce with Java 8 Streams.
It gives the following output,
Even numbers:
2
4
6
8
10
Squares:
1
4
9
16
25
36
49
64
81
100
Sum: 55
Sum of squares of even numbers: 220
Longest word > 4 chars (uppercase): STREAM
Terminal vs Intermediate Operations: Intermediate (lazy, return Stream): filter(), map(), flatMap(), sorted(), distinct(), limit(), peek(). Terminal (eager, trigger processing): forEach(), collect(), reduce(), count(), findFirst(), anyMatch(), toArray().
|
|