JAVA二级分组3种方式,看了很多文章才发现这个非常灵活的用法:Collectors.groupingBy分2级,最后再把其中对象值取出来放Set中

public static void main(String[] args) {
        List<Student> list = new ArrayList();
        Student st1 = new Student("123","ap","成功");
        Student st2 = new Student("123","ap","成功");
        Student st3 = new Student("123","exp","成功");
        Student st4 = new Student("123","exp","不成功");
        list.add(st1);
        list.add(st2);
        list.add(st3);
        list.add(st4);
        Map<String, Map<String,List<Student>>> map1 = list.stream().collect(Collectors.groupingBy(Student::getBatchNumber,
                Collectors.groupingBy(Student::getType,Collectors.toList())));
        System.out.println("1===================================================");
        System.out.println(map1.toString());
        
        System.out.println("2===================================================");
        Map<String, Map<String,String>> map2 = list.stream().collect(Collectors.groupingBy(Student::getBatchNumber,
                Collectors.toMap(Student::getType, Student::getStatus,(v1,v2)->v2)));
        System.out.println(map2.toString());
        
        System.out.println("3===================================================");
        Map<String, Map<String, Set<String>>> map3 = list.stream().collect(Collectors.groupingBy(Student::getBatchNumber,
                Collectors.groupingBy(Student::getType,Collectors.mapping(Student::getStatus, Collectors.toSet()))));
        System.out.println(map3.toString());
        System.out.println("===================================================");
    }

结果如下: 

1===================================================
{123={exp=[Student(batchNumber=123, type=exp, status=成功), Student(batchNumber=123, type=exp, status=不成功)], ap=[Student(batchNumber=123, type=ap, status=成功), Student(batchNumber=123, type=ap, status=成功)]}}

2===================================================
{123={exp=不成功, ap=成功}}

3===================================================
{123={exp=[成功, 不成功], ap=[成功]}}
===================================================

Process finished with exit code 0

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值