我們有一張地圖 Students { studentId : StudentData }。StudentData 是一個具有學生屬性的 POJO。要求是讓所有學生都具有 attribute isCurrent==true。如果是,則提取學生的城市屬性。這將用于增加 studentpercity 地圖的計數{ city : count }Students.entrySet()
.stream()
.filter(x -> true == x.getValue().isCurrent())
.forEach(x -> {
studentpercity(x.getValue().getCity(), (studentpercity.getOrDefault(x.getValue().getCity(), 0) + 1));
});最終輸出將是一張城市地圖,以計算“當前”學生的數量。有沒有更有效的方法來實現這一目標?
2 回答

寶慕林4294392
TA貢獻2021條經驗 獲得超8個贊
你可以這樣做,
Map<String, Long> studentPerCity = students.values().stream().filter(StudentData::isCurrent) .collect(Collectors.groupingBy(StudentData::getCity, Collectors.counting()));

搖曳的薔薇
TA貢獻1793條經驗 獲得超6個贊
另一種選擇可能是這樣的:
students.values().stream() .filter(StudenData::isCurrent) .map(StudenData::getCity) .forEach(city -> studentpercity(city, studentpercity.getOrDefault(city, 0) + 1));
但是,關于您對“迭代”的評論。在單個流中(如您的示例),每個元素僅迭代一次。這意味著流中的每個操作都將在每個元素上應用一次,并且只有在之前沒有被過濾掉的情況下才會應用。
添加回答
舉報
0/150
提交
取消