Question 10
Back to Exercise
Group a list of words into anagram families using groupingBy on each word's sorted letters, keep only families with 2+ words, and print them sorted by family size then key.
Solution
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class Main {
static String key(String w) {
return w.chars().sorted().collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append).toString();
}
public static void main(String[] args) {
List<String> words = List.of("listen", "silent", "enlist", "rat", "tar", "art", "stone", "notes", "java", "evil", "vile", "live", "veil");
words.stream()
.collect(Collectors.groupingBy(Main::key))
.entrySet().stream()
.filter(e -> e.getValue().size() > 1)
.sorted(Comparator.comparing((Map.Entry<String, List<String>> e) -> e.getValue().size()).reversed().thenComparing(Map.Entry::getKey))
.forEach(e -> System.out.println(e.getKey() + " " + e.getValue()));
}
}
eilv [evil, vile, live, veil] art [rat, tar, art] eilnst [listen, silent, enlist] enost [stone, notes]
The three-argument collect builds the sorted key from an IntStream of characters. Sorting entries by size (then key) makes the output deterministic.
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!