Streams
Streams
Streams
ADVANCED PROGRAMMING
CONTENTS
• Streams
• Mappers
• Reducers
• Collectors
https://www.gartner.com/en/documents/3906723/stream-processing-the-new-data-processing-paradigm
1
07/07/2023
STREAM<T>
see: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/stream/Stream.html
STREAMS
2
07/07/2023
STREAM<T>
intermediate
values terminal
stream …
source operation
operations
7.3, 4.5, 9.1, 8.0, 7.3, 1.2, 4.5, 9.1, 8.0, 1.2 7.3, 9.1, 8.0, 7.3, 9.1, 8.0
List<double> Stream<double> Stream<double> 6
grades .stream() .filter(x à x >= 5.5) .count() 6
Stream<double> Stream<double> int
List<double>
• Computation on the source data is only performed when the terminal operation is initiated.
3
07/07/2023
METHOD-CHAINING IN STREAMS
• This contributes to
• flexibility of applying combinations of operations in any order
• brevity of code
• readability of code
4
07/07/2023
STREAM OPERATIONS:
MAPPERS AND REDUCERS
STREAM OPERATIONS:
INTERMEDIATE MAPPERS AND FINAL REDUCERS
• mapper: • reducer:
selects and transforms values aggregates/combines values
• .map(Function<T,R>) • .anyMatch(Predicate<T>),
.mapToInt(), .mapToDouble() .allMatch(...), .noneMatch(…)
.filter(Predicate<T>) .sum()
.distinct() .count()
.limit(maxSize) .reduce(BinaryOperator<T>)
.flatMap(Function<T,Stream<R>>
10
10
5
07/07/2023
EXAMPLE
start
Stream<Book>
reducer Predicate<Book>
11
11
EXAMPLE
mapper:
get numPages from
each processed book
instance method
reducer: for ToIntFunction<Book>
adds all numbers of pages
12
12
6
07/07/2023
EXAMPLE
default for
a missing Optional
13
13
Optional<T>
14
14
7
07/07/2023
15
15
EXAMPLE
BinaryOperator<Book>
which each time retains the book
get the final surviving book with the longest title
from Optional<Book>
16
16
8
07/07/2023
STREAM<BOOK> REDUCER
Book-abc
Book-defgh
Book-i
Book-jk Book-lmnopq
Book-jk Book-defgh
Book-abc
Book-i
Book-lmnopq
Set<Book> Stream<Book> Optional<Book>
17
17