【发布时间】:2021-09-10 03:55:21
【问题描述】:
我遇到了一个问题,我需要计算 Iterable 中的字符串数并将总和存储在 Map 中。我想出了以下命令式解决方案:
private static Map<String, Integer> generateCounts(Iterable<String> words) {
Map<String, Integer> wordCounts = new HashMap<>();
for (String word : words) {
if (wordCounts.containsKey(word)) {
Integer count = wordCounts.get(word);
wordCounts.replace(word, count + 1);
} else {
wordCounts.put(word, 1);
}
}
return wordCounts;
}
什么是利用函数式方法而不是像上面那样的命令式方法的解决方案?
【问题讨论】:
-
final Map<String, Integer> wordCount = StreamSupport.stream(words.spliterator(), false).collect(Collectors.toMap(Function.identity(), word -> 1, Integer::sum));(Ideone demo)
标签: java java-8 functional-programming imperative-programming