Oracle Certified Professional Java Se 8 Programmer · Free Practice Question Hard
Question 7
Given code of Test.java file:
- package com.udayan.ocp;
- import java.util.stream.Stream;
- public class Test {
- public static void main(String[] args) {
- Stream<Double> stream = Stream.generate(() -> new Double("1.0")).limit(10);
- System.out.println(stream.filter(d -> d > 2).allMatch(d -> d == 2));
- }
- }
What will be the result of compiling and executing Test class?
- A false
- B true
Reveal correct answer
Correct answer: B
Explanation
Method signatures:
boolean anyMatch(Predicate<? super T>) : Returns true if any of the stream element matches the given Predicate. If stream is empty, it returns false and predicate is not evaluated.
boolean allMatch(Predicate<? super T>) : Returns true if all the stream elements match the given Predicate. If stream is empty, it returns true and predicate is not evaluated.
boolean noneMatch(Predicate<? super T>) : Returns true if none of the stream element matches the given Predicate. If stream is empty, it returns true and predicate is not evaluated.
In the given code,
Stream.generate(() -> new Double("1.0")).limit(10); => returns a Stream<Double> containing 10 elements and each element is 1.0.
stream.filter(d -> d > 2) => returns an empty stream as given predicate is not true for even 1 element.
allMatch method, when invoked on empty stream, returns true.
Discussion
Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.
