Stream Collectors — Concept Check
Questions on Stream Collectors. Use Collectors to accumulate stream elements into lists, maps, grouped structures, joined strings, and custom containers.
Questions in this quiz
8 questions on Stream Collectors — Concept Check. Work through them here, then start the quiz to answer them and see your score.
1.You have a list of employees and you want to create a Map where the keys are department names and the values are lists of employee names. Which collector should you use?
- ACollectors.partitioningBy with Collectors.mapping
- BCollectors.joining with a delimiter
- CCollectors.groupingBy with Collectors.mapping
- DCollectors.toMap with a merge function
2.In Java streams, you want to concatenate a list of names into a single string, separated by commas, and enclosed in square brackets. Which collector achieves this?
- ACollectors.groupingBy with delimiter
- BCollectors.toMap with prefix and suffix
- CCollectors.joining with prefix and suffix
- DCollectors.toList with delimiter
3.You are using Collectors.toMap to map employee names to their ages, but you encounter a duplicate key error. What should you do to resolve this?
- AUse Collectors.groupingBy instead
- BSwitch to Collectors.toList
- CRemove duplicate keys from the source data
- DProvide a merge function to handle duplicates
4.You want to split a list of numbers into two groups: those greater than 5 and those not. Which collector should you use?
- ACollectors.toMap with a key extractor
- BCollectors.joining with a delimiter
- CCollectors.partitioningBy with a predicate
- DCollectors.groupingBy with a predicate
5.A developer uses Collectors.toUnmodifiableList but tries to add an element to the resulting list. What happens?
- AThe element is added successfully
- BAn UnsupportedOperationException is thrown
- CA ConcurrentModificationException is thrown
- DThe list is silently modified
6.You need to calculate both the minimum and maximum values of a stream in one pass. Which collector should you use?
- ACollectors.teeing with minBy and maxBy
- BCollectors.partitioningBy with min and max
- CCollectors.toMap with min and max
- DCollectors.groupingBy with summarizingInt
7.When using Collectors.groupingBy, what is the result if you do not provide a downstream collector?
- AAn error due to missing downstream collector
- BA Map with counts of grouped elements
- CA single list of all elements
- DA Map with lists of grouped elements
8.A developer believes that Collectors.toMap automatically handles key collisions by keeping the first value. What is the actual behavior?
- AIt silently overwrites with the last value
- BIt keeps the first value automatically
- CIt merges values by default
- DIt throws an IllegalStateException