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.
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.