Java OCA OCP Practice Question 1715

Question

What does the following output?

import java.util.ArrayDeque;
import java.util.Deque;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.stream.Stream;

public class Main {

   public static void main(String[] args) {
      Set<String> set = new HashSet<>();
      set.add("tire-");
      List<String> list = new LinkedList<>();
      Deque<String> queue = new ArrayDeque<>();
      queue.push("wheel-");
      Stream.of(set, list, queue).flatMap(x -> x.stream()).forEach(System.out::print);
   }// ww w .j a  v  a  2 s  . c  o m
}
  • A. [tire-][wheel-]
  • B. tire-wheel-
  • C. None of the above.
  • D. The code does not compile.


B.

Note

The flatMap() method is used to turn a stream of streams into a one-dimensional stream.

This means it gets rid of the empty list and flattens the other two.

Option A is incorrect because this is the output you'd get using the regular map() method.

Option B is correct because it flattens the elements.

Notice how it doesn't matter that all three elements are different types of Collection implementations.




PreviousNext

Related