0
点赞
收藏
分享

微信扫一扫

JAVA8 Collectors.groupingBy


1.按长度对字符串进行分组

List<String> list = Arrays.asList("a", "bb", "cc", "ddd");
Map<Integer, List<String>> result = list.stream().collect(Collectors.groupingBy(String::length));
System.out.println(result);
// {1=[a], 2=[bb, cc], 3=[ddd]}

2.根据ExcelEntity的某个字段进行分组

List<ExcelEntity> list = new ArrayList<>();
ExcelEntity entity1 = new ExcelEntity();
entity1.setGlobalNo("001");
entity1.setUserId("zhangsan");
entity1.setAddress("北京");
entity1.setGoodsCd("A001");
list.add(entity1);
ExcelEntity entity2 = new ExcelEntity();
entity2.setGlobalNo("002");
entity2.setUserId("lisi");
entity2.setAddress("上海");
entity2.setGoodsCd("A002");
list.add(entity2);
ExcelEntity entity3 = new ExcelEntity();
entity3.setGlobalNo("003");
entity3.setUserId("wangwu");
entity3.setAddress("辽宁");
entity3.setGoodsCd("A003");
list.add(entity3);

Map<String, List<ExcelEntity>> map = list.stream()
        .collect(Collectors.groupingBy(ExcelEntity::getGlobalNo));
System.out.println(map);
// {001=[com.ExcelEntity@214c265e], 002=[com.ExcelEntity@448139f0], 003=[com.ExcelEntity@7cca494b]}

3.计数

Map<String, Long> map = list.stream()
        .collect(Collectors.groupingBy(ExcelEntity::getGlobalNo, Collectors.counting()));
System.out.println(map);
// {001=1, 002=1, 003=2}

 

举报

相关推荐

0 条评论