Group By Property in Java: Explanation & Practice

Group elements by a property

Problem summary

Write a program that groups words by their first letter.

Starter code

import java.util.*;

public class Main {
    public static void main(String[] args) {
        List<String> words = Arrays.asList("apple", "banana", "apricot", "berry", "avocado"); // Test case 1
        
        // Group by first letter
        // Print: letter: [words]
    }
}

Expected output and test cases

  • Grouped by letter
    a: [apple, apricot, avocado]
    b: [banana, berry]
  • Different groups
    c: [cat, car]
    d: [dog]
  • All same letter
    x: [x, xx, xxx]

Hints

  1. Use Map<Character, List<String>>
  2. Get first char with charAt(0)
  3. computeIfAbsent() for cleaner code

Related Collections exercises

Practice all Collections exercises · Run this idea in the Java compiler