gpt4 book ai didi

Java 8 List to EnumMap with sums

转载 作者:搜寻专家 更新时间:2023-10-31 19:37:04 25 4
gpt4 key购买 nike

我有以下类(class):

public class Mark {

private Long id;

private Student student;

private Integer value = 0;

private Subject subject;

}

public enum Subject {

MATH,
CHEMISTRY

}

我必须收到 EnumMap<Subject, Integer> ,其中值是 Mark 中所有值的总和.
List<Mark> 的示例:

Mark(..., value = 1, subject = MATH)
Mark(..., value = 2, subject = MATH)
Mark(..., value = 5, subject = CHEMISTRY)

有了这个值,我必须收到以下 EnumMap :

MATH             -> 3
CHEMISTRY -> 5

我认为应该用 Collectors::groupingBy 来完成, 但我不明白如何获得 EnumMap和他的值(value)。

最佳答案

 markList.stream().collect(
groupingBy(
Mark::getSubject,
() -> new EnumMap<Subject, Integer>(Subject.class),
summingInt(Mark::getValue)));

关于Java 8 List to EnumMap with sums,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41732240/

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