Oracle Certified Professional Java Se 11 Developer · Free Practice Question Easy
Question 91
Question ID: UKOCP27770
Given code:
- package com.udayankhattry.ocp;
- import java.util.stream.Stream;
- public class Test {
- public static void main(String[] args) {
- Stream<Double> stream = Stream.generate(() -> Double.valueOf("1.0"))
- .limit(10);
- System.out.println(stream.filter(d -> d > 2)
- .allMatch(d -> d == 2));
- }
- }
What is the result?
- A false
- B true
Reveal correct answer
Correct answer: B
Explanation
UKOCP27770:
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.
