Item 45. Stream
์คํธ๋ฆผ ์ฐ์ฐ
๊ณผํ ์คํธ๋ฆผ
// ๊ธฐ์กด ์ฝ๋
class Anaagram {
public static void main(String[] args) throws IOException {
Path dictionary = Paths.get(args[0]);
int minGroupSize = Integer.parseInt(args[1]);
Map<String, Set<String>> groups = new HashMap<>();
try (Scanner s = new Scanner(dictionary)) {
while (s.hasNext()) {
String word = s.next();
groups.computeIfAbsent(alphabetize(word), (unused) -> new TreeSet<>()).add(word);
}
}
for (Set<String> group : groups.values()) {
if (group.size() >= minGroupSize) {
System.out.println(group.size() + ": " + group);
}
}
}
private static String alphabetize(String s) {
char[] a = s.toCharArray();
Arrays.sort(a);
return new String(a);
}
}
// Stream ์ฌ์ฉ
class Anaagram {
public static void main(String[] args) throws IOException {
Path dictionary = Paths.get(args[0]);
int minGroupSize = Integer.parseInt(args[1]);
try (Stream<String> words = Files.lines(dictionary)) {
words.collect(groupingBy(word -> word.chars().sorted()
.collect(StringBuilder::new, (sb, c) -> sb.append((char) c), StringBuilder::append).toString()))
.values().stream().filter(group -> group.size() >= minGroupSize)
.map(group -> group.size() + ": " + group).forEach(System.out::println);
}
}
}๊ธฐ๋ณธ ํ์
์ด ์๋ ์คํธ๋ฆผ ์ฌ์ฉ
์๋ง๋ ์คํธ๋ฆผ ์ฌ์ฉ
Last updated