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
- Use Map<Character, List<String>>
- Get first char with charAt(0)
- computeIfAbsent() for cleaner code
Related Collections exercises
- Practice List Intersection in Java
- Practice Sort Map by Value in Java
- Practice Simple LRU Cache in Java
Practice all Collections exercises · Run this idea in the Java compiler