Java 如何筛选具有先决条件的组?

Java 如何筛选具有先决条件的组?,java,java-stream,Java,Java Stream,请输入下一个代码: public static Map<String, Double> getSumOfPricesPerCategoryOver(){ List<Videogame> number = videogames; Map<String, Double> counted = number .stream() .collect(Collectors.groupingBy(Videogame::getCateg

请输入下一个代码:

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;
    }
public静态映射getSumOfPricesPerCategoryOver(){
列表编号=视频游戏;
地图计数=数字
.stream()
.collect(Collectors.groupingBy(视频游戏::getCategoria,Collectors.summingDouble(视频游戏::getPrecio));
返回计数;
}
问题


我想筛选价格总和高于200的类别组,有什么想法吗?

您可以使用
分区方式对地图进行分区:

导入静态java.util.stream.collector.*;
地图更新地图=
number.stream()
.收集(分组方式)(视频游戏::getCategoria,
分区方式(e->e.getPrice()>200));
这里,
分类
,值是另一个
映射
,它将(
/
)划分为两类
视频游戏
:1)价格>200和价格200 地图更新地图= number.stream() 收集(收集)然后( 分组方式(视频游戏::getCategoria,汇总(视频游戏::getPrice)), m->{m.values().removeIf(e->e<200);返回m;});
您可以
筛选
条目:

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;
}
public静态映射getSumOfPricesPerCategoryOver(){
列表编号=视频游戏;
地图计数=数字
.stream()
.collect(Collectors.groupingBy(视频游戏::getCategoria,Collectors.summingDouble(视频游戏::getPrecio)))
.entrySet().stream()
.filter(CategoryTotalPrice->CategoryTotalPrice.getValue()>200)
.collect(Collectors.toMap(Map.Entry::getKey,Map.Entry::getValue));
返回计数;
}

或者,您可以在返回之前删除条目,这将使超过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;
}
public静态映射getSumOfPricesPerCategoryOver(){
列表编号=视频游戏;
地图计数=数字
.stream()
.collect(Collectors.groupingBy(视频游戏::getCategoria,Collectors.summingDouble(视频游戏::getPrecio));
counted.values().removeIf(值->值>200);
返回计数;
}

非常感谢,效果很好。@aisak很高兴它起了作用。