Group Words by First Letter
Explore Java Collectors to perform powerful data aggregation operations on streams. You will use collectors like groupingBy, partitioningBy, and counting to organize data into maps and compute statistics in a single pass.
Focus on understanding how collectors transform stream elements into complex data structures like nested maps and summary statistics objects. This is essential for data analysis and reporting tasks.
Example 1:
Input: words = ["apple", "apricot", "banana", "berry"]
Output: {a: ["apple", "apricot"], b: ["banana", "berry"]}
Explanation: Group words by first letter.
Example 2:
Input: numbers = [1, 2, 3, 4, 5, 6]
Output: {even: [2, 4, 6], odd: [1, 3, 5]}
Explanation: Partition numbers by parity.
Example 3:
Input: ages = [25, 30, 25, 40, 30, 25]
Output: {25: 3, 30: 2, 40: 1}
Explanation: Count frequency of each age.
Algorithm Flow

Best Answers
import java.util.*;
import java.util.stream.Collectors;
class Solution {
public Map<Character, List<String>> groupWords(List<String> words) {
return words.stream()
.collect(Collectors.groupingBy(
word -> word.charAt(0),
Collectors.toList()
));
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this problem.
