Group Anagrams in Java: Explanation & Practice
Group words that are anagrams of each other
Problem summary
Given a list of words, group them by anagrams.
Starter code
import java.util.*;
public class Main {
public static void main(String[] args) {
String[] words = {"eat", "tea", "tan", "ate", "nat", "bat"};
// Group anagrams together
// Print each group on a line
}
}Expected output and test cases
- Grouped anagrams
[eat, tea, ate] [tan, nat] [bat]
- All anagrams
[abc, bca, cab]
- No anagrams
[a] [b] [c]
Hints
- Sort each word's characters as key
- Use Map<String, List<String>>
- Same sorted chars = anagrams
Related Collections exercises
- Practice Merge K Sorted Lists in Java
- Practice Stack Using Queues in Java
- Practice Sliding Window Maximum in Java
Practice all Collections exercises · Run this idea in the Java compiler