我们在利用java8 Lambda 表达式将集合中对象的属性转成Map时就会出现 Duplicate key xxxx , 说白了也就是key 重复了!案例如下:
@Data
@NoArgsConstructor
@AllArgsConstructor
class Person{
private String className;
private String studentName;
}
public class DuplicateKey {
public static void main(String[] args) {
List list = new ArrayList<>();
list.add(new Person("一班", "小明"));
list.add(new Person("二班", "小芳"));
list.add(new Person("一班", "小华"));
Map map = list.stream().collect(Collectors.toMap(Person::getClassName, Person::getStudentName));
System.out.println(map);
}
}
此时就会出现Duplicate key xxxx 这个问题,那怎么解决呢?其实很简单,有三种方法
- 我们需要使用toMap的另外一个重载的方法!
Collectors.toMap(keyMapper, valueMapper, mergeFunction)
作用:重复时采用后面的value 覆盖前面的value
Mapmap = list.stream().collect(Collectors.toMap(Person::getClassName, Person::getStudentName,(key1,key2)->key1));
- 重复时将之前的value 和现在的value拼接或相加起来;
Mapmap = list.stream().collect(Collectors.toMap(Person::getClassName, Person::getStudentName,(key1,key2)->key1+", "+key2));
- 将重复key的数据变成一个集合!
Map> map = list.stream(). collect(Collectors.toMap(Person::getClassName, s -> { List studentNameList = new ArrayList<>(); studentNameList.add(s.getStudentName()); return studentNameList; }, (List value1, List value2) -> { value1.addAll(value2); return value1; })); System.out.println(map);



