zoukankan      html  css  js  c++  java
  • 使用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}

  • 相关阅读:
    课堂笔记-------字符串类型string------练习
    网络设计中需要考虑的时延latency差异
    ceph calamari 监控系统安装 on ubuntu 14.04
    Ceph性能优化总结(v0.94)
    创意点子
    “CEPH浅析”系列之八——小结
    “Ceph浅析”系列之七——关于Ceph的若干想法
    “CEPH浅析”系列之六——CEPH与OPENSTACK
    “Ceph浅析”系列之五——Ceph的工作原理及流程
    Ceph浅析”系列之四——Ceph的结构
  • 原文地址:https://www.cnblogs.com/lsy-bolg/p/14133688.html
Copyright © 2011-2022 走看看