一哨毁、概述
有這樣一個(gè)需求仔燕,在一個(gè)list集合中的對(duì)象有相同的name颠毙,我需要把相同name的對(duì)象的total進(jìn)行匯總計(jì)算,并且根據(jù)total倒序排序肌索。使用java stream來(lái)實(shí)現(xiàn)這個(gè)需求蕉拢,這里做一個(gè)記錄,希望對(duì)有需求的同學(xué)提供幫助诚亚。
二晕换、根據(jù)對(duì)象指定字段分組排序
使用java stream 計(jì)算的過(guò)程如下圖:
image.png
下面是實(shí)現(xiàn)的代碼示例:
/**
* 定義一個(gè)對(duì)象,這里使用了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)建幾個(gè)對(duì)象放在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進(jìn)行分組
.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());
}
}
輸出結(jié)果如下:
image.png