Start learning free

LESSON 228 OF 285 · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

Group Words by First Letter in Java: A HashMap of Lists

Practice Read the full explanation

Given an array words of lowercase words, group the words by their first letter. Return a HashMap where each key is a first letter, written as a one-character string, and its value is an array of all the words that start with that letter.

Inside each group, keep the words in the order they have in words. The order of the entries in the HashMap doesn't matter.

Example 1:

Input: words = ["apple", "banana", "avocado", "blueberry", "cherry"]
Output: {"a": ["apple", "avocado"], "b": ["banana", "blueberry"], "c": ["cherry"]}
Explanation: "apple" and "avocado" start with "a", "banana" and "blueberry" start with "b", and "cherry" is alone under "c".

Example 2:

Input: words = ["dog", "cat", "deer", "cow", "duck"]
Output: {"d": ["dog", "deer", "duck"], "c": ["cat", "cow"]}
Explanation: "dog" comes before "deer" and "duck" in words, so it comes first in the "d" group too.

Example 3:

Input: words = ["hello"]
Output: {"h": ["hello"]}
Explanation: One word makes one group.

Rules:

  • words has at least one word.
  • Every word has at least one letter and only lowercase letters a-z.
  • A word that appears more than once in words appears as many times in its group.
STEP 1 OF 6
    Ctrl + Enter to check

    JAVA · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

    Group Words By First Letter in Java, explained

    Problem overview

    The method groupByFirstLetter receives an array of lowercase words and returns a HashMap<String, List<String>>. Each key is a first letter, written as a one-character string, and its value is the list of all words that start with that letter, in the order they have in words.

    For ["apple", "banana", "avocado", "blueberry", "cherry"] the result is {a=[apple, avocado], b=[banana, blueberry], c=[cherry]}. For ["dog", "cat", "deer", "cow", "duck"] it is {c=[cat, cow], d=[dog, deer, duck]}: "dog" comes before "deer" and "duck" in the input, so it comes first in its group too. One word, ["hello"], makes one group, {h=[hello]}. A word that appears twice appears twice in its group, and the order of the entries in the map doesn't matter.

    Approach: a map whose values are lists

    This is a counting loop in which the value is a list instead of a number. For each word, find the group of its first letter and append the word to it. The first word with a new letter has no group yet, so the group must be created before it is used. After that, the loop is a single pass: each word belongs to exactly one group.

    The order inside a group needs no extra work. The loop meets the words in their original order, and add appends at the end of a list, so each group keeps the input order.

    Step by step

    1. Create the map. HashMap<String, List<String>> groups = new HashMap<>(); maps a one-letter String to a List of words.
    2. Loop over the words with for (String word : words).
    3. Take the first letter with word.substring(0, 1), the characters from index 0 up to, but not including, index 1. The keys are strings, so slicing is simpler than charAt(0), which gives a char.
    4. Create the group if it's missing. If !groups.containsKey(first), put a new empty ArrayList under first. A later word with the same letter finds the list already there.
    5. Add the word. groups.get(first) returns the list stored in the map, not a copy, so calling add on it changes the list inside the map.
    6. Return groups after the loop.

    The solution in Java

    class Solution {
        public HashMap<String, List<String>> groupByFirstLetter(String[] words) {
            HashMap<String, List<String>> groups = new HashMap<>();
            for (String word : words) {
                String first = word.substring(0, 1);
                if (!groups.containsKey(first)) {
                    groups.put(first, new ArrayList<>());
                }
                groups.get(first).add(word);
            }
            return groups;
        }
    }
    

    Java details worth knowing:

    • new ArrayList<>() inside put. The empty diamond is filled in from the map's declared value type, List<String>, so the compiler knows it is an ArrayList<String>. The map's declared type is the interface List, which is why any list implementation fits.
    • get without the check. For a missing key, get returns null. Calling add on it would throw a NullPointerException, which is why the group is created first.
    • Lists are references. The map holds a reference to each list. Because get returns that same reference, no put is needed after add.
    • Shorter forms. groups.computeIfAbsent(first, k -> new ArrayList<>()).add(word); does the check, the creation and the add in one statement. On the second example it also gives {c=[cat, cow], d=[dog, deer, duck]}. The lesson's version spells out each case.
    • substring on an empty string. "".substring(0, 1) throws a StringIndexOutOfBoundsException. The lesson guarantees that every word has at least one letter.

    Complexity

    Time: O(n) for n words, ignoring the length of the words: each word costs a constant number of map and list operations on average. Space: O(n), because every word ends up in one list.

    Edge cases and common mistakes

    • Replacing the list. Putting a new ArrayList for every word, without the containsKey check, leaves only the last word of each group.
    • Forgetting the !. Without it the group is created only when it already exists, and the first get returns null.
    • Using charAt(0) as the key. That is a char, and it would be boxed into a Character. The map's key type is String, so the call doesn't match.
    • Repeated words. ["go", "go"] gives {g=[go, go]}. Both stay, because a list keeps duplicates.
    • Counting instead of grouping. If the values were numbers, you would lose the words themselves. The point of the list is to keep them.

    Testing

    • ["apple", "banana", "avocado", "blueberry", "cherry"] gives {a=[apple, avocado], b=[banana, blueberry], c=[cherry]}.
    • ["dog", "cat", "deer", "cow", "duck"] gives {c=[cat, cow], d=[dog, deer, duck]}.
    • ["hello"] gives {h=[hello]}.
    • ["go", "go"] gives {g=[go, go]}.
    Keep going with Java1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free