英文:
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<String, Integer> productMap = new HashMap<>();
Integer counter = 0;
for (Product product : products) {
for (Quality quality : product.getQualities()) {
if (quality.evaluate() > 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 -> product.getQualities().stream())
.filter(q -> q.evaluate() > Float.NEGATIVE_INFINITY)
.map(Quality::getName)
.forEach(qName -> 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.
专注分享java语言的经验与见解,让所有开发者获益!
评论