使用Java8中group by分组并对各个小组进行操作
1 public static void main(String[] args) { 2 EmployDO zhangsan = new EmployDO.Builder().name("张三").sex("男").position("职员").status("在职").age("20").build(); 3 EmployDO lisi = new EmployDO.Builder().name("李四").sex("男").position("职员").status("在职").age("24").build(); 4 EmployDO wangwu = new EmployDO.Builder().name("王五").sex("男").position("职员").status("离职").age("21").build(); 5 EmployDO yangliu = new EmployDO.Builder().name("杨六").sex("男").position("职员").status("在职").age("25").build(); 6 EmployDO lihua = new EmployDO.Builder().name("李华").sex("女").position("领导").status("在职").age("20").build(); 7 EmployDO xiaohua = new EmployDO.Builder().name("小花").sex("女").position("职员").status("离职").age("23").build(); 8 EmployDO xiaofeng = new EmployDO.Builder().name("小凤").sex("女").position("领导").status("在职").age("25").build(); 9 List<EmployDO> employDOS = Arrays.asList(zhangsan, lisi, wangwu, yangliu, lihua, xiaohua, xiaofeng); 10 // 根据sex分组 11 Map<String, List<EmployDO>> map = employDOS.stream().collect(Collectors.groupingBy(EmployDO::getSex)); 12 System.out.println(JSON.toJSONString(map)); 13 // 根据sex分组,计算出每个小组的人数 14 Map<String, Long> countMap = employDOS.stream().collect(Collectors.groupingBy(employ -> employ.getSex(), Collectors.counting())); 15 System.out.println(JSON.toJSONString(countMap)); 16 }
输出 :
map输出:
{"女":[{"age":"20","name":"李华","position":"领导","sex":"女","status":"在职"},{"age":"23","name":"小花","position":"职员","sex":"女","status":"离职"},{"age":"25","name":"小凤","position":"领导","sex":"女","status":"在职"}],"男":[{"age":"20","name":"张三","position":"职员","sex":"男","status":"在职"},{"age":"24","name":"李四","position":"职员","sex":"男","status":"在职"},{"age":"21","name":"王五","position":"职员","sex":"男","status":"离职"},{"age":"25","name":"杨六","position":"职员","sex":"男","status":"在职"}]}
countMap输出:
{"女":3,"男":4}