fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.util.stream.*;
  5. import java.lang.*;
  6. import java.io.*;
  7.  
  8. /* Name of the class has to be "Main" only if the class is public. */
  9. class Ideone {
  10. public static final String keyOf(String word) {
  11. char[] chars = word.toCharArray();
  12. Arrays.sort(chars);
  13. return new String(chars);
  14. }
  15.  
  16. public static final List<List<String>> groupAnagrams(Stream<String> stream) {
  17. Map<String, List<String>> mapped = stream.collect(Collectors.groupingBy(w -> keyOf(w)));
  18. return new ArrayList<>(mapped.values());
  19. }
  20.  
  21. public static void main (String[] args) throws java.lang.Exception {
  22. String[][] words = {{"bat", "tab", "tea", "eat", "ate"}, {"foo", "boo", "moo", "omo"}};
  23. for (String[] wa : words) {
  24. String out = groupAnagrams(Stream.of(wa))
  25. .stream()
  26. .map(wl -> wl.stream().collect(Collectors.joining("\", \"", " [\"", "\"]")))
  27. .collect(Collectors.joining(",\n", "[\n", "\n]"));
  28. System.out.println(out);
  29. }
  30. }
  31. }
Success #stdin #stdout 0.09s 711680KB
stdin
Standard input is empty
stdout
[
  ["tea", "eat", "ate"],
  ["bat", "tab"]
]
[
  ["boo"],
  ["foo"],
  ["moo", "omo"]
]