import java.util.Map;
import java.util.List;
import java.util.Arrays;
import java.util.HashMap;
import java.util.ArrayList;
// Groups a list of strings into sublists of anagrams.
public class GroupAnagrams {
public static List<List<String>> groupAnagrams(List<String> words) {
if (words == null) {
throw new IllegalArgumentException("Input must be a list of strings.");
}
Map<String, List<String>> map = new HashMap<>();
for (String word : words) {
if (word == null) {
throw new IllegalArgumentException("All elements in the list must be non-null strings.");
}
// Sort characters
char[] chars = word.toCharArray();
Arrays.sort(chars);
String sorted = new String(chars);
// Group words by their sorted key
map.computeIfAbsent(sorted, k -> new ArrayList<>()).add(word);
}
// Return grouped anagrams as a list of lists
return new ArrayList<>(map.values());
}
public static void main(String[] args) {
try {
List<String> lst = Arrays.asList("eat", "tea", "rop", "ate", "nat", "orp", "tan", "bat", "pro");
List<List<String>> result = groupAnagrams(lst);
// Print result
System.out.println("[");
for (List<String> group : result) {
System.out.print(" [ ");
for (int i = 0; i < group.size(); i++) {
System.out.print("'" + group.get(i) + "'");
if (i + 1 < group.size()) {
System.out.print(", ");
}
}
System.out.println(" ]");
}
System.out.println("]");
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
}
/*
run:
[
[ 'rop', 'orp', 'pro' ]
[ 'eat', 'tea', 'ate' ]
[ 'bat' ]
[ 'nat', 'tan' ]
]
*/