diff --git a/docs/notes/45. 明智审慎地使用Stream.md b/docs/notes/45. 明智审慎地使用Stream.md index 3aca15e..0668acb 100644 --- a/docs/notes/45. 明智审慎地使用Stream.md +++ b/docs/notes/45. 明智审慎地使用Stream.md @@ -25,8 +25,8 @@ public class Anagrams { try (Scanner s = new Scanner(dictionary)) { while (s.hasNext()) { String word = s.next(); - groups.computeIfAbsent(alphabetize(word), - (unused) -> new TreeSet<>()).add(word); + groups.computeIfAbsent(alphabetize(word), + (unused) -> new TreeSet<>()).add(word); } } @@ -50,19 +50,19 @@ public class Anagrams { ```java // Overuse of streams - don't do this! public class Anagrams { - public static void main(String[] args) throws IOException { - Path dictionary = Paths.get(args[0]); - int minGroupSize = Integer.parseInt(args[1]); - try (Stream 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); + public static void main(String[] args) throws IOException { + Path dictionary = Paths.get(args[0]); + int minGroupSize = Integer.parseInt(args[1]); + try (Stream 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); } } } @@ -76,18 +76,18 @@ public class Anagrams { // Tasteful use of streams enhances clarity and conciseness public class Anagrams { - public static void main(String[] args) throws IOException { - Path dictionary = Paths.get(args[0]); - int minGroupSize = Integer.parseInt(args[1]); + public static void main(String[] args) throws IOException { + Path dictionary = Paths.get(args[0]); + int minGroupSize = Integer.parseInt(args[1]); - try (Stream words = Files.lines(dictionary)) { - words.collect(groupingBy(word -> alphabetize(word))) - .values().stream() - .filter(group -> group.size() >= minGroupSize) - .forEach(g -> System.out.println(g.size() + ": " + g)); - } - } - // alphabetize method is the same as in original version + try (Stream words = Files.lines(dictionary)) { + words.collect(groupingBy(word -> alphabetize(word))) + .values().stream() + .filter(group -> group.size() >= minGroupSize) + .forEach(g -> System.out.println(g.size() + ": " + g)); + } + } + // alphabetize method is the same as in original version } ```