Code Logo

Group Words by First Letter

Published at13 Jan 2026
Medium 50 views
Like20

You are given a list of words and need to group them by their first letter.

The result should be a map where the key is the starting character and the value is the list of words that begin with that character. If two words start with the same letter, they belong in the same group. If a letter only appears once as a starting character, that group still exists with a one-word list.

For example, ["apple", "banana", "ant"] becomes a map where 'a' points to ["apple", "ant"] and 'b' points to ["banana"]. A list like ["cat", "dog", "car"] creates a 'c' group and a 'd' group.

So the task is to organize the words by their first character using Java grouping collectors.

Example Input & Output

Example 1
Input
words = ["only"]
Output
{"o": ["only"]}
Explanation

Single word grouping.

Example 2
Input
words = ["cat", "dog", "car"]
Output
{"c": ["cat", "car"], "d": ["dog"]}
Explanation

Grouping multiple words with the same prefix.

Example 3
Input
words = ["apple", "banana", "ant"]
Output
{"a": ["apple", "ant"], "b": ["banana"]}
Explanation

Words grouped by their first letter.

Algorithm Flow

Recommendation Algorithm Flow for Group Words by First Letter
Recommendation Algorithm Flow for Group Words by First Letter

Solution Approach

This problem is a classic use case for Java's Collectors.groupingBy. The goal is not to transform every word into something new and it is not to count them. Instead, we want to classify each word and let Java collect all words from the same class into one list.

Here, the classification rule is very small: look at the first character of each word. In Java, that can be written as word -> word.charAt(0).

Once we have that rule, the stream pipeline becomes:

return words.stream().collect(Collectors.groupingBy(word -> word.charAt(0)));

This says: stream through the list, compute a grouping key for each word, and build a map from each key to the words that produced it.

The nice part is that groupingBy automatically creates the lists for us. We do not need to check whether a key already exists, manually create a new list, or append by hand. Java handles that collector logic internally.

The solution runs in O(n) time with respect to the number of words, ignoring the cost of storing the output itself. Conceptually, it is a clean example of classification-based collection: determine the key for each item, then let the collector place it into the correct bucket.

Best Answers

java - Approach 1
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()
                   ));
    }
}