I have class Data which have 4 fields and have list of values then i want replace each row groupby year and sum value for same year using java 8 and stream. please see below code and output.
class Data {
int id;
int year;
String name;
double value;
}
List<Data> list = new ArrayList<>();
list.add(new Data(101, 2018, "AAA", 20));
list.add(new Data(102, 2019, "BBB", 30));
list.add(new Data(103, 2020, "CCC", 10));
list.add(new Data(104, 2019, "DDD", 50));
list.add(new Data(105, 2020, "EEE", 40));
list.add(new Data(106, 2020, "FFF", 60));
First code try:
list.stream().collect(Collectors.groupingBy(Data::getYear, Collectors
.summingDouble(Data::getValue)));
Second code try:
list.stream().collect(Collectors.toMap(value -> value.getYear(), Function.identity(),
(a, b) -> new Data(a.getId(), a.getYear(), a.getName(), a.getValue() + b.getValue()))).values()
.forEach(value -> System.out.println(value));
Output:
id year name value
101 2018 "AAA" 20
102 2019 "BBB" 80
103 2020 "CCC" 110
Expected Output:
id year name value
101 2018 "AAA" 20
102 2019 "BBB" 80
103 2020 "CCC" 110
104 2019 "DDD" 80
105 2020 "EEE" 110
106 2020 "FFF" 110