直接代码:上面代码是int,下面是bigDecimal
public class StreamTest {
public static void main(String[] args) {
List<Good> list = new ArrayList<>();
Good g1 = new Good(1,"x",1);
Good g2 = new Good(2,"x",1);
Good g3 = new Good(1,"x",2);
Good g4 = new Good(3,"y",8);
list.add(g1);
list.add(g2);
list.add(g3);
list.add(g4);
// 创建几个对象放在list集合中
List<Good> collect1 = list.stream()
// 根据name进行分组
.collect(Collectors.groupingBy(Good::getId))
.entrySet()
.stream()
.map(entry -> {
int key = entry.getKey();
List<Good> value = entry.getValue();
Integer sum = value.stream().mapToInt(Good::getTotal).sum();
return new Good(key,sum);
})
// 根据total倒序排序
// .sorted(Comparator.comparing(Good::getTotal).reversed())
.collect(Collectors.toList());
System.out.println(collect1.toString());
}
}
@Data
@AllArgsConstructor
class Good {
private int id;
private String name;
private int total;
public Good(int id, int total) {
this.id = id;
this.total = total;
}
}
结果:
[Good(id=1, name=null, total=3), Good(id=2, name=null, total=1), Good(id=3, name=null, total=8)]
BigDecimal:
package com.ali99.java.test.stream;
import lombok.AllArgsConstructor;
import lombok.Data;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class StreamTest {
public static void main(String[] args) {
List<Good> list = new ArrayList<>();
Good g1 = new Good(1,"x",new BigDecimal(1));
Good g2 = new Good(2,"x",new BigDecimal(1));
Good g3 = new Good(1,"x",new BigDecimal(2));
Good g4 = new Good(3,"y",new BigDecimal(8));
list.add(g1);
list.add(g2);
list.add(g3);
list.add(g4);
// 创建几个对象放在list集合中
List<Good> collect1 = list.stream()
// 根据name进行分组
.collect(Collectors.groupingBy(Good::getId))
.entrySet()
.stream()
.map(entry -> {
int key = entry.getKey();
List<Good> value = entry.getValue();
BigDecimal sum = value.stream().map(Good::getTotal).reduce(BigDecimal.ZERO,BigDecimal::add);
return new Good(key,sum);
})
// 根据total倒序排序
// .sorted(Comparator.comparing(Good::getTotal).reversed())
.collect(Collectors.toList());
System.out.println(collect1.toString());
}
}
@Data
@AllArgsConstructor
class Good {
private int id;
private String name;
private BigDecimal total;
public Good(int id, BigDecimal total) {
this.id = id;
this.total = total;
}
}
结果一样