Lambda 实战-集合分组统计

package com.lingoace.edu.util;

import lombok.Data;

import java.util.ArrayList;
import java.util.List;
import java.util.LongSummaryStatistics;
import java.util.Map;
import java.util.stream.Collectors;

public class Test {
    @Data
    public static class DataStatisticsResultMiddle{
        private String datas;
        private String carrierid;
        private Long enusers;

    }

    public static void main(String[] args) {

        List<DataStatisticsResultMiddle> li = new ArrayList<>();
        DataStatisticsResultMiddle middle1 = new DataStatisticsResultMiddle();
        middle1.setDatas("2019");
        middle1.setCarrierid("1");
        middle1.setEnusers(100L);
        DataStatisticsResultMiddle middle2 = new DataStatisticsResultMiddle();
        middle2.setDatas("2019");
        middle2.setCarrierid("1");
        middle2.setEnusers(150L);
        DataStatisticsResultMiddle middle3 = new DataStatisticsResultMiddle();
        middle3.setDatas("2019");
        middle3.setCarrierid("1");
        middle3.setEnusers(200L);

        DataStatisticsResultMiddle middle4 = new DataStatisticsResultMiddle();
        middle4.setDatas("2019");
        middle4.setCarrierid("2");
        middle4.setEnusers(400L);
        DataStatisticsResultMiddle middle5 = new DataStatisticsResultMiddle();
        middle5.setDatas("2019");
        middle5.setCarrierid("2");
        middle5.setEnusers(500L);
        DataStatisticsResultMiddle middle6 = new DataStatisticsResultMiddle();
        middle6.setDatas("2019");
        middle6.setCarrierid("2");
        middle6.setEnusers(600L);

        li.add(middle1);
        li.add(middle2);
        li.add(middle3);
        li.add(middle4);
        li.add(middle5);
        li.add(middle6);


        //单个字段,分组求和(datas),主要Collectors.counting(),可以根据需求进行count 或sum 等操作
        Map<String, Long> enusersCollect1 =
                li.stream().collect(Collectors.groupingBy(DataStatisticsResultMiddle:: getCarrierid, Collectors.counting()));
        Long enusers = enusersCollect1.get("3");
        System.out.println(enusers);
    }
}

你可能感兴趣的:(lambda,java,后端)