使用java stream對(duì)集合中的對(duì)象按指定字段進(jìn)行分組統(tǒng)計(jì)并排序

一、概述

有這樣一個(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
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容