Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Grouping Anagrams Using Hash Maps in Java

Tech May 19 1
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().

Tags: Java

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.