【问题标题】:Functional approach to storing element counts in Map在 Map 中存储元素计数的函数式方法
【发布时间】: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&lt;String, Integer&gt; wordCount = StreamSupport.stream(words.spliterator(), false).collect(Collectors.toMap(Function.identity(), word -&gt; 1, Integer::sum)); (Ideone demo)

标签: java java-8 functional-programming imperative-programming


【解决方案1】:

如果您擅长返回Map&lt;String, Long&gt;,那么您可以执行以下操作:

StreamSupport.stream(words.spliterator(), false /*sequential*/)
             .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

或者,不使用流,你可以这样做:

Map<String, Integer> wordCounts = new HashMap<>();
words.forEach(word -> wordCounts.merge(word, 1, Integer::sum));
return wordCounts;

这里代码中的if-elsemerge 函数替换:

if (wordCounts.containsKey(word)) {
    Integer count = wordCounts.get(word);
    wordCounts.replace(word, count + 1);
} else {
    wordCounts.put(word, 1);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-15
    相关资源
    最近更新 更多