Oracle Certified Professional Java Se 8 Programmer · Free Practice Question Easy
Question 27
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<Integer> stream = Stream.iterate(1, i -> i + 1);
- System.out.println(stream.anyMatch(i -> i > 1));
- }
- }
What will be the result of compiling and executing Test class?
- A true
- B Nothing is printed on to the console as code runs infinitely
- C false
- D true is printed on to the console and code runs infinitely
Reveal correct answer
Correct answer: A
Explanation
stream => {1, 2, 3, 4, 5, ... }. It is an infinite stream.
Predicate 'i -> i > 1' returns true for any Integer greater than 1.
As 2 > 1, so true is printed and operation is terminated. Code doesn't run infinitely.
NOTE: 'stream.allMatch(i -> i > 1)' returns false as 1st element of the stream (1) returns false for the predicate and 'stream.noneMatch(i -> i > 1)' returns false as 2nd element of the stream (2) returns true for the predicate.
Discussion
Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.
