OCP 17 Exam - chapter 10 notes
OCP 17 Exam - chapter 10 notes
Streams fundamentals
- “Streams are evaluated lazily, which means intermediate operations are not executed until a terminal operation is invoked.”
1 2 3 4 5
var ints = new ArrayList<Integer>(); ints.add(1); var intsStream = ints.stream(); ints.add(2); System.out.println(intsStream.count()); // prints 2 !!
- “Streams are single-use; stream must have at most one terminal operation.” Exception will be thrown when terminal operation is called again on stream reference: (review Q.3)
1 2 3 4 5
var stream = Stream.iterate(0, i -> i+1).limit(10); var m1 = stream.noneMatch(i -> i < 0); // var m2 = stream.anyMatch(i -> i > 5); // throws java.lang.IllegalStateException: stream has already been operated upon or closed var m2 = true; System.out.println(m1 + " | " + m2);
Note:
java.util.Collection.parallelStream
can be used to speedup processing of large stream with time-consuming operations.
Infinite streams
- infinite streams can be created with
Stream#iterate
orStream#generate
:1 2 3 4 5 6 7 8 9 10 11
Stream.iterate(1, i -> i + 1).limit(10) .forEach(i -> System.out.print(i +",")); // prints 1,2,3,4,5,6,7,8,9,10, System.out.println(""); Stream.iterate(1, i -> i <= 10, i -> i + 1) .forEach(i -> System.out.print(i +",")); // prints 1,2,3,4,5,6,7,8,9,10, System.out.println(""); Stream.generate(() -> new Random().nextInt(10)).limit(10) .forEach(i -> System.out.print(i +",")); // prints random numbers System.out.println("");
infinite stream w/o stop (e.g.
limit(10)
) causes program hang! (review Q.2)
Note: only
findFirst
andfindAny
terminate infinite stream. Methods that sometimes terminates are:allMatch
,anyMatch
,noneMatch
.
Reduce operations
Stream#reduce
- if you don’t specify identity parameter, then return type isOptional
, see method signatures:1 2
T reduce(T identity, BinaryOperator<T> accumulator); Optional<T> reduce(BinaryOperator<T> accumulator);
Stream#collect
is called mutable reduction as we can accumulate an intermediate result, see method signature: ```java
This post is licensed under CC BY 4.0 by the author.