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)
));