Java Program to Group Anagrams

 

Program Code


import java.util.*;

public class AnagramGrouper {
    
    /**
     * Groups anagrams from a list of strings.
     *
     * @param strs List of strings to group into anagrams.
     * @return A list of lists, where each sublist contains anagrams.
     */
    public List<List> groupAnagrams(String[] strs) {
        Map<String, List> anagramMap = new HashMap<>();
        
        for (String str : strs) {
            // Sort the characters of the string to generate a key
            char[] charArray = str.toCharArray();
            Arrays.sort(charArray);
            String key = new String(charArray);
            
            // Grouping anagrams using the sorted string as key
            anagramMap.putIfAbsent(key, new ArrayList<>());
            anagramMap.get(key).add(str);
        }
        
        // Returning the values as a list of lists
        return new ArrayList<>(anagramMap.values());
    }

    public static void main(String[] args) {
        AnagramGrouper ag = new AnagramGrouper();
        String[] input = {"eat", "tea", "tan", "ate", "nat", "bat"};
        
        List<List> groupedAnagrams = ag.groupAnagrams(input);
        System.out.println(groupedAnagrams);
    }
}
        

Program Structure Explanation

The program is structured around a class named AnagramGrouper, which contains a method called groupAnagrams.

  1. Imports:
    The program imports the necessary classes from the Java standard library: java.util.* for collections.
  2. groupAnagrams Method:
    • This method takes an array of strings as input and returns a list of lists containing grouped anagrams.
    • A HashMap is used to store the sorted string as the key and a list of corresponding anagrams as the value.
    • For each string, its characters are sorted to form a key. The original string is then added to the appropriate list in the map.
    • Finally, the method returns the values of the map as a list of lists, containing the grouped anagrams.
  3. main Method:
    This method serves as the entry point for the program. It creates an instance of AnagramGrouper, defines a sample array of strings, and invokes the groupAnagrams method.

Execution

When executed, the program will group the provided strings into lists of anagrams and print the result to the console.

Example Output


        [[bat], [nat, tan], [ate, eat, tea]]
        

Conclusion

This program efficiently groups anagrams by leveraging sorting and hashing, making it both intuitive and performant.

 

Leave a Reply

Your email address will not be published. Required fields are marked *