如何过滤带有前提条件的组?



有下一个代码:

public static Map<String, Double> getSumOfPricesPerCategoryOver(){
List<Videogame> number = videogames;

Map<String, Double> counted = number
.stream()
.collect(Collectors.groupingBy(Videogame::getCategoria, Collectors.summingDouble(Videogame::getPrecio)));

return counted;
}

问题

我想过滤价格总和高于 200 的类别组,知道吗?

您可以使用partitioningBy对映射进行分区:

import static java.util.stream.Collectors.*;
Map<String, Map<Boolean, List<Videogame>>> updatedMap = 
number.stream()
.collect(groupingBy(Videogame::getCategoria, 
partitioningBy(e -> e.getPrice() > 200)));

在这里,keyCategoria,值是将(true/false)分为两类Videogame的另一种Map:1)价格>200和价格<= 200。

编辑 1:
我看到了其他答案并重读了这个问题。OP打算根据价格总和过滤类别。

此要求的构造为:

import static java.util.stream.Collectors.*;
// Key: Category, Value: Sum of all prices
// The resultant map contains only those categories that have total price > 200
Map<String, Integer> updatedMap = 
number.stream()
.collect(collectingAndThen(
groupingBy(Videogame::getCategoria, summingInt(Videogame::getPrice)), 
m -> {m.values().removeIf(e -> e < 200); return m;}));

您可以filter条目:

public static Map<String, Double> getSumOfPricesPerCategoryOver(){
List<Videogame> number = videogames;
Map<String, Double> counted = number
.stream()
.collect(Collectors.groupingBy(Videogame::getCategoria, Collectors.summingDouble(Videogame::getPrecio)))
.entrySet().stream()
.filter(categoryToTotalPrice -> categoryToTotalPrice.getValue() > 200)
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
return counted;
}

或者,您可以在返回之前删除条目,这样可以明显地过滤掉超过 200 的值:

public static Map<String, Double> getSumOfPricesPerCategoryOver(){
List<Videogame> number = videogames;
Map<String, Double> counted = number
.stream()
.collect(Collectors.groupingBy(Videogame::getCategoria, Collectors.summingDouble(Videogame::getPrecio)));
counted.values().removeIf(value -> value > 200);
return counted;
}

最新更新