OCP Question 21, Explanation

Given the code fragment:

List<Integer> list1 = Arrays.asList(1, 2);
List<Integer> list2 = Arrays.asList(3, 4);
//line n1

Which code fragment, when inserted at line n1, prints 1 2 3 4?

A. Stream.of(list1, list2)
         .flatMap(x -> x.stream())
         .forEach(x -> System.out.print(x + " "));
B. Stream.of(list1, list2)
         .flatMap(x -> x.intStream())
         .forEach(x -> System.out.print(x + " "));
C. list1 .stream()
         .flatMap(list2.stream().flatMap(x -> x.stream())
         .forEach(x -> System.out.println(x + " "));
D. Stream.of(list1, list2)
         .flatMapToInt(x -> x.stream())
         .forEach(x -> System.out.print(x + " "));

The correct answer is A.

Stream.of(T… vals) creates a sequential stream composed of vals, then flatMap() transforms each List into its own stream, whose elements get printed.

As for Option B, List has no intStream() method, and Option D’s flatMapToInt() is supposed to return an IntStream rather than Stream<Integer>. To demonstrate that option D could be persuaded to compile and even work as requested we might, for example, change its LE into something that returns an IntStream directly populated with our lists’ elements:

Stream.of(list1, list2)
      .flatMapToInt(x -> IntStream.of(x.get(0), x.get(1)))
      .forEach(x -> System.out.print(x + " "));       // 1 2 3 4

Option C is syntactically invalid, as well, as it transforms list2 into a stream of Integer objects and then tries to call stream() on each one of them in flatMap() once again. And I would like to point out here that option C wouldn’t be correct even when valid: its println() would output values in a column rather than a row. On the other hand, as you’ve already witnessed in Problem 15, the exam is sloppy with coding even correct options…

Note to self: add a link to the Prep Notes on Stream.

Leave Comment

Your email address will not be published.