第 46 条:优先使用Stream中无副作用的函数

2021-05-24  本文已影响0人  综合楼
优先使用Stream中无副作用的函数.jpeg
// Uses the streams API but not the paradigm--Don't do this!
        Map<String, Long> freq = new HashMap<>();
        Map<String, String> freq2 = new HashMap<>();
        String[] file = {"a", "b", "b","c"};
        Stream<String> words = Stream.of(file);
            words.forEach(word -> {
                freq.merge(word.toLowerCase(), 1L, Long::sum);
                freq2.merge(word.toLowerCase(), "-", (first,second)->first+second);
            });
        System.out.println(freq);
        System.out.println(freq2);
// Proper use of streams to initialize a frequency table
        Map<String, Long> freq;
        String[] file = {"a", "b", "b","c"};
        Stream<String> words = Stream.of(file);
        freq = words.collect(groupingBy(String::toLowerCase, counting()));
        System.out.println(freq);
上一篇下一篇

猜你喜欢

热点阅读