一、问题描述
一个list数组,在转换成Map集合的时候报的错,原因是作为key的元素在list中有两个
二、原因分析
tomap时遇到了重复键的问题,这里举个例子并记录一下解决方法。
1.先准备一组学生列表数据,其中id是有重复的
List<Student> stuList = new ArrayList<>();
stuList.add(new Student("1","11"));
stuList.add(new Student("1","211"));
stuList.add(new Student("2","22"));
2.当我们使用普通toMap操作时,就会出现Duplicate key
Map<String, Student> map = stuList.stream()
.collect(Collectors.toMap(item -> item.getId(),item -> item));
三、解决方案
解决方式就在Java8提供的Collectors.toMap() 方法中,其第三个参数就是当出现 duplicate key的时候的处理方案
//取前面的值,舍弃后面的值
Map<String, Student> idMap = stuList.stream()
.collect(Collectors.toMap(Student::getId, Function.identity(), (v1, v2) -> v1));
//取后面的值,舍弃前面的值
Map<String, Student> idMap2 = stuList.stream()
.collect(Collectors.toMap(Student::getId, Function.identity(), (v1, v2) -> v2));