LAMBDA表达式List 转Map 几种处理

1、第一种,List<Student> 转化Map<String,String>

Map<String,String> map = list.stream()
        .collect(Collectors.toMap(
                Student::getName, Student::getAge, (k1, k2) -> k2));

 2、第二种,List<Student> 转化Map<String,List<String>>

// 基础分组
Map<String, List<String>> schoolToNames = studentList.stream()
    .collect(Collectors.groupingBy(
        Student::getSchool,
        Collectors.mapping(Student::getName, Collectors.toList())  // 学校对应姓名列表
    ));

// ‌多级分组 按学校和年龄两级分组
Map<String, Map<Integer, List<String>>> multiLevelMap = studentList.stream()
    .collect(Collectors.groupingBy(
        Student::getSchool,
        Collectors.groupingBy(
            Student::getAge,
            Collectors.mapping(Student::getName, Collectors.toList())
        )
    ));

 3、第三种,List<Student> 转化Map<String,Student>

Map<String,Student> map = list.stream()
        .collect(Collectors.toMap(
                Student::getName, student->student, (k1,k2)->k1);

 4、第四种,List<Student> 转化Map<String,List<Student>>

// 普通分组
Map<String, List<Student>> map = studentList.stream()
    .collect(Collectors.groupingBy(Student::getClassName));  // 按班级分组

// 条件过滤分组
Map<String, List<Student>> map= list.stream()
        .filter(s -> s.getScore() > 60)  // 只保留及格学生
        .collect(Collectors.groupingBy(Student::getClassName));

// 多级分组

Map<String, Map<String, List<Student>>> multiMap = studentList.stream()
    .collect(Collectors.groupingBy(
        Student::getClassName,
        Collectors.groupingBy(Student::getGender)
    ));

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值