← All Exercises
Group Anagrams with Sorted Keys
intermediatejava
Background
Anagram grouping tests canonicalization: two inputs are equivalent when a stable key derived from each is equal. It is also a common collection and stream grouping exercise.
Problem
Given a list of words, group words that are anagrams of each other. Comparison is case-insensitive, groups are ordered by their sorted-letter key, and words inside each group are sorted.
Input
A list of non-empty words containing letters only; case is ignored; the list may contain duplicate spellings.
Output
One line per anagram group showing the sorted words in brackets, ordered by the normalized sorted-letter key; duplicates stay in their group.
Sample tests
Sample 1
Input: listen, silent, enlist, google, gooegl, cat
Expected: [cat] [gooegl, google] [enlist, listen, silent]
Sample 2
Input: Cat, act, tac
Expected: [Cat, act, tac]
Your solution
Learning objective
Canonicalize strings, use computeIfAbsent with TreeMap ordering, and sort nested collections deterministically.