Java Stream API - Collectors Explained
1. [Link]()
[Link]() is a terminal operation in the Stream API that collects the stream
elements into a List. It does not perform any transformation or grouping. It simply
accumulates all the elements as they appear in the stream into a new List.
Example:
List<String> names = [Link]("Alice", "Bob", "Charlie");
List<String> collected = [Link]().collect([Link]());
[Link](collected); // Output: [Alice, Bob, Charlie]
2. [Link]()
[Link]() is used to group stream elements by a classifier function. It returns
a Map where the keys are the result of applying the classifier function, and the values are
Lists of items that matched the key.
Example:
List<String> names = [Link]("Alice", "Bob", "Charlie", "David");
Map<Integer, List<String>> grouped = [Link]()
.collect([Link](name -> [Link]()));
[Link](grouped); // Output: {3=[Bob], 5=[Alice, David], 7=[Charlie]}
3. Summary Table
Collector Result Type Purpose
[Link]() List<T> Collects elements into a list
[Link](...) Map<K, List<T>> Groups elements by a key
derived from a function