因为Map是key-value键值对格式存储的,所以在实际项目中可以取出list中的唯一字段(主键)作为key,该字段对应的对象作为value,转化成map来操作。
实际场景比如一个学生的集合list,还有一个学生成绩的集合list,把学生成绩的集合匹配到学生集合上;
//学生集合 ListstudentList=StudentService.findStudentsByIds(ids); //分数集合 List scoreList=ScoreService.findScoreByIds(ids); //学生ID为key,分数对象为value Map map= scoreList.stream().collect(Collectors.toMap(Score::getStuId, x ->x)); //循环放入student中 List studentResponse=new List (); for(Student student:studentList){ Score score=map.get(student.getId()); student.setscore(score.getScore()); studentResponse.add(student); }
重点:
//list转map Mapmap= scoreList.stream().collect(Collectors.toMap(Score::getStuId, x ->x));



