Java - Print Anagrams Together

Problem Statement

Given an array of strings, group all anagrams together.

Example

Input:

words = ["cat", "dog", "tac", "god", "act"]

Output:

[["cat", "tac", "act"], ["dog", "god"]]

Explanation:

"cat", "tac", and "act" are anagrams.

"dog" and "god" are anagrams.

Approach

Use HashMap (Dictionary)

Sort each word and use it as a key in a HashMap.

Store the original words in a list under the same key.

Print all grouped anagrams.

Java Code

import java.util.*;

public class AnagramGroups {

    public static List<List<String>> groupAnagrams(String[] words) {

        Map<String, List<String>> anagramGroups = new HashMap<>();

        // Store words in map by sorting them as keys

        for (String word : words) {

            char[] charArray = word.toCharArray();

            Arrays.sort(charArray);

            String sortedWord = new String(charArray);

 

            anagramGroups.putIfAbsent(sortedWord, new ArrayList<>());

            anagramGroups.get(sortedWord).add(word);

        }

        return new ArrayList<>(anagramGroups.values());

    }

    public static void main(String[] args) {

        String[] words = {"cat", "dog", "tac", "god", "act"};

        System.out.println(groupAnagrams(words));

    }

}