优先使用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);
网友评论