Java OCA OCP Practice Question 2252

Question

What is the result of the following?

import java.util.stream.*; 

public class Main { 

   public static void main(String[] args) { 
      Integer result = /*w w w.j  a v a  2 s.c o  m*/
         Stream.of(getNums(9, 8), getNums(22, 33))  // c1 
         .filter(x -> !x.isEmpty())                 // c2 
         .flatMap(x -> x)                           // c3 
         .max((a, b) -> a - b)                      // c4 
         .get(); 
      System.out.println(result); 
   } 
   private static Stream<Integer> getNums(int num1, int num2) { 
      return Stream.of(num1, num2); 
   } 
} 
  • A. The code compiles and outputs 8.
  • B. The code compiles and outputs 33.
  • C. The code does not compile due to line c1.
  • D. The code does not compile due to line c2.
  • E. The code does not compile due to line c3.
  • F. The code does not compile due to line c4.


D.

Note

Line c1 correctly creates a stream containing two streams.

Line c2 does not compile since x is a stream, which does not have an isEmpty() method.

Therefore, Option D is correct.

If the filter() call was removed, flatMap() would correctly turn the stream into one with four Integer elements and max() would correctly find the largest one.

The Optional returned would contain 33, so Option B would be the answer in that case.




PreviousNext

Related