Junior
What is the purpose of the collect() method in Java streams?
sobes.tech AI
Answer from AI
The collect() method in Java Stream API is used to gather stream elements into a container such as List, Set, Map, or to perform a general operation on the elements.
It takes one or more parameters: a supplier, an accumulator, a combiner, or a ready-made Collector. Essentially, collect() reduces the stream to a single result.
Examples of usage with predefined collectors from the Collectors class:
-
Collecting into a list:
// Collect all stream elements into an ArrayList list.stream() .collect(Collectors.toList()); -
Collecting into a set:
// Collect unique stream elements into a HashSet list.stream() .collect(Collectors.toSet()); -
Collecting into a map:
// Collect elements into a map where the key is id, and the value is the object list.stream() .collect(Collectors.toMap(/* keyMapper */ obj -> obj.getId(), /* valueMapper */ obj -> obj)); -
Grouping:
// Group by the type field, returns Map<Type, List<Object>> list.stream() .collect(Collectors.groupingBy(/* classifier */ obj -> obj.getType())); -
Joining strings:
// Join strings with a separator list.stream().map(String::valueOf) .collect(Collectors.joining(", "));
You can also create your own Collector for more specific collection tasks.