Java OCA OCP Practice Question 1739

Question

When working with a Stream<String>,

which of these types can be returned from the collect() terminal operator by passing arguments to Collectors.groupingBy()?

  • I. Map<Integer, List<String>>
  • II. Map<Boolean, HashSet<String>>
  • III. List<String>
  • A. I
  • B. II
  • C. I and II
  • D. I, II, and III


C.

Note

The groupingBy() collector always returns a Map, so III can't be right.

The other two are definitely possible.

To get I, you can group using a Function that returns an Integer such as s.collect(Collectors.groupingBy(String::length)).

To get II, you need to group using a Function that returns a Boolean and specify the type,

such as s.collect(Collectors.groupingBy(String::isEmpty,Collectors.toSet())).

The autoboxing is used for both.

Option C is correct.




PreviousNext

Related