Grouping Anagrams Using Hash Maps in Java
class Solution {
public List<List<String>> clusterAnagrams(String[] inputs) {
Map<String, List<String>> groups = new HashMap<>();
for (String item : inputs) {
char[] temp = item.toCharArray();
Arrays.sort(temp);
String signature = new String(temp);
groups.computeIfAbsent(signature, k -> new ArrayList<>()).add(item);
}
return new ArrayList<>(groups.values());
}
}
Strings in Java are immutable and lack a built-in sorting method, so converting them to a character array is necessary to apply sorting. Prior to JDK 9, toCharArray() produced a char[]; from JDK 9 onward, it yields a byte[] for strings containing only ASCII characters, switching to char[] when non-ASCII symbols are present. This method creates a copy of the underlying character sequence.
Alternatively, sorting can be performed via streams:
String ordered = Arrays.stream(str.split(""))
.sorted()
.collect(Collectors.joining());
The split("") call uses an empty regular expression, which divides the string into individual single-character strings. For example, "bac" becomes [ "b", "a", "c" ]. Arrays.stream() transforms this array into a stream, and sorted() arranges elements using their natural ordering defined by Comparable<String>, which relies on Unicode code points.
The computeIfAbsent method checks wheether the specified key exists in the map. If absent, it applies the given mapping function to produce a new value, stores it under that key, and returns it. In this context, the key is the sorted character signature of a word, and the value is a list of words sharing that signature. The lambda _ -> new ArrayList<>() ignores the input parameter type, equivallent to explicitly declaring k -> new ArrayList<>(). After ensuring the list exists, the current string is appended via add().