Java OCA OCP Practice Question 1703

Question

What is the output of the following?

import java.util.Map;
import java.util.function.BinaryOperator;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Main {

   public static void main(String[] args) {
      Stream<String> s = Stream.of("speak", "bark", "meow", "growl");
      BinaryOperator<String> merge = (a, b) -> a;
      Map<Integer, String> map = s.collect(Collectors.toMap(String::length, k -> k, merge));
      System.out.println(map.size() + " " + map.get(4));

   }//w  w  w . j  a  v a 2  s.  com
}
  • A. 2 bark
  • B. 2 meow
  • C. 4 bark
  • D. None of the above


A.

Note

The collector tries to use the number of characters in each stream element as the key in a map.

This works fine for the first two elements, speak and bark, because they are of length 5 and 4, respectively.

When it gets to meow, it sees another key of 4.

The merge function says to use the first one, so it chooses bark for the value.

Similarly, growl is 5 characters, but the first value of speak is used.

There are only two distinct lengths, so Option A is correct.




PreviousNext

Related