
一、概述
有這樣一個需求,在一個list集合中的對象有相同的name,我需要把相同name的對象的total進行匯總計算,并且根據(jù)total倒序排序。使用java stream來實現(xiàn)這個需求,這里做一個記錄,希望對有需求的同學提供幫助。
二、根據(jù)對象指定字段分組排序
使用java stream 計算的過程如下圖:

image.png
下面是實現(xiàn)的代碼示例:
/**
* 定義一個對象,這里使用了lombok的注解
*/
@Data
@Accessors(chain = true)
class Good {
private String name;
private Integer total;
}
public class Test4 {
public static void main(String[] args) {
List<Good> list = new ArrayList<>();
// 創(chuàng)建幾個對象放在list集合中
list.add(new Good().setName("xiaomi").setTotal(2));
list.add(new Good().setName("huawei").setTotal(2));
list.add(new Good().setName("apple").setTotal(2));
list.add(new Good().setName("xiaomi").setTotal(2));
List<Good> collect1 = list.stream()
// 根據(jù)name進行分組
.collect(Collectors.groupingBy(Good::getName))
.entrySet()
.stream()
.map(entry -> {
String key = entry.getKey();
List<Good> value = entry.getValue();
Integer sum = value.stream().mapToInt(Good::getTotal).sum();
return new Good().setName(key).setTotal(sum);
})
// 根據(jù)total倒序排序
.sorted(Comparator.comparing(Good::getTotal).reversed())
.collect(Collectors.toList());
System.out.println(collect1.toString());
}
}
輸出結果如下:

image.png