美文网首页
第 45 条:谨慎使用Stream

第 45 条:谨慎使用Stream

作者: 综合楼 | 来源:发表于2021-05-22 10:21 被阅读0次
    谨慎使用Stream.jpeg
    // 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<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);
            }
        }
    }
    
    // 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]);
            try (Stream<String> 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
    }
    
    // Iterative Cartesian product computation
    private static List<Card> newDeck() {
        List<Card> result = new ArrayList<>();
        for (Suit suit : Suit.values())
            for (Rank rank : Rank.values())
                result.add(new Card(suit, rank));
        return result;
    }
    
    // Stream-based Cartesian product computation
    private static List<Card> newDeck() {
        return Stream.of(Suit.values())
            .flatMap(suit ->
                Stream.of(Rank.values())
                    .map(rank -> new Card(suit, rank)))
            .collect(toList());
    }
    

    相关文章

      网友评论

          本文标题:第 45 条:谨慎使用Stream

          本文链接:https://www.haomeiwen.com/subject/pzvwdltx.html