gpt4 book ai didi

java - 在 map 中提取值

转载 作者:搜寻专家 更新时间:2023-11-01 02:18:56 24 4
gpt4 key购买 nike

我们有一张 map Students { studentId : StudentData }。
StudentData 是一个具有学生属性的 POJO。
要求是让所有具有属性 isCurrent==true 的学生。
如果是,则提取学生的城市属性。
这将用于增加 studentpercity map 的计数 { city : count }

Students.entrySet()
.stream()
.filter(x -> true == x.getValue().isCurrent())
.forEach(x -> {
studentpercity(x.getValue().getCity(), (studentpercity.getOrDefault(x.getValue().getCity(), 0) + 1));
});

最终输出将是一张城市 map ,用于计算“当前”学生的数量。
有没有更有效的方法来实现这一目标?

最佳答案

你可以这样做,

Map<String, Long> studentPerCity = students.values().stream().filter(StudentData::isCurrent)
.collect(Collectors.groupingBy(StudentData::getCity, Collectors.counting()));

关于java - 在 map 中提取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57158610/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com