在Java 8中从对象快速创建带有计数器的映射的方法是:

huangapple 未分类评论56阅读模式
英文:

short way to create map from object with counter in java 8

问题

以下是使用stream()功能获取相同功能的简短方式:

HashMap<String, Integer> productMap = products.stream()
    .flatMap(product -> product.getQualities().stream())
    .filter(quality -> quality.evaluate() > Float.NEGATIVE_INFINITY)
    .collect(Collectors.groupingBy(Quality::getName, Collectors.summingInt(quality -> 1)));
英文:

Is there a short way using stream() functionality to get the following functionaity?

HashMap&lt;String, Integer&gt; productMap = new HashMap&lt;&gt;();
Integer counter = 0;
for (Product product : products) {
    for (Quality quality :  product.getQualities()) {
        if (quality.evaluate() &gt; Float.NEGATIVE_INFINITY) {
            if (productMap.containsKey(quality.getName())) {
                productMap.replace(quality.getName(), counter + 1);
            } else {
                productMap.put(quality.getName(), counter + 1);
            }
        }
    }
}

答案1

得分: -1

正如其他人指出的,counter 从未被递增。另外,正如 @Holger 提到的,没有必要检查 productMap.containsKey()。如果你真的想要做完全相同的事情,你可以尝试以下代码:

products.stream()
         .flatMap(product -> product.getQualities().stream())
         .filter(q -> q.evaluate() > Float.NEGATIVE_INFINITY)
         .map(Quality::getName)
         .forEach(qName -> productMap.put(qName, counter + 1));

首先,使用 flatMap()products 流转换为 qualities 流。然后过滤出那些评估值大于 NEGATIVE_INFINITY 的部分,然后将每个部分的名称进行转换 (map()),最后将它们放入地图中。

英文:

As others have pointed out, counter is never incremented. Also, as @Holger mentioned, there is no need to check if productMap.containsKey(). If you really want to do the exact same thing you can try:

products.stream()
         .flatMap(product -&gt; product.getQualities().stream())
         .filter(q -&gt; q.evaluate() &gt; Float.NEGATIVE_INFINITY)
         .map(Quality::getName)
         .forEach(qName -&gt; productMap.put(qName, counter + 1));

First, use flatMap() to transform the stream of products into a stream of qualities. Then filter out the ones that evaluate to more than NEGATIVE_INFINITY, than transform (map()) each one to its name and finally put them in the map.

huangapple
  • 本文由 发表于 2020年7月28日 23:33:09
  • 转载请务必保留本文链接:https://java.coder-hub.com/63137782-2.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定