我有一個Map<LocalDateTime, Set<Vote>> map = new HashMap<>();我必須計算票數(shù)并將其放入按 localDateTime 分組的新地圖中。我不知道如何用流來做到這一點。我的返回值必須是Map<LocalDateTime, Integer>.如何在 Java 8 中使用流來做到這一點?
1 回答

牧羊人nacy
TA貢獻1862條經(jīng)驗 獲得超7個贊
由于您已經(jīng)有一個Map<LocalDateTime,Set<Vote>>
,因此Vote
實例已按 分組LocalDateTime
。您需要做的就是對每個投票值求和Set<Vote>
:
Map<LocalDateTime, Integer> voteSums = map.entrySet() .stream() .collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue() .stream() .mapToInt(Vote::getVoteValue) .sum()));
您應(yīng)該在其中替換為返回您希望求和的值的類方法getVoteValue
的實際名稱。Vote
或者,如果您只想知道Vote
每個鍵有多少個實例,您可以這樣寫:
Map<LocalDateTime, Integer> voteCounts = map.entrySet() .stream() .collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue().size()));
添加回答
舉報
0/150
提交
取消