Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,845 questions

51,766 answers

573 users

How to convert a list of strings and group all the anagrams into sublists in Java

1 Answer

0 votes
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' ]
]
 
*/

 



answered Nov 14, 2025 by avibootz
edited Nov 15, 2025 by avibootz
...