我们在利用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<Person> list = new ArrayList<>();
list.add(new Person("一班", "小明"));
list.add(new Person("二班", "小芳"));
list.add(new Person("一班", "小华"));
Map<String, String> map = list.stream().collect(Collectors.toMap(Person::getClassName, Person::getStudentName));
System.out.println(map);
}
}
? 此时就会出现Duplicate key ?xxxx?这个问题,那怎么解决呢?其实很简单,有三种方法? ? ?
????????Collectors.toMap(keyMapper, valueMapper, mergeFunction)
????????作用:重复时采用后面的value 覆盖前面的value
Map<String, String> map = list.stream().collect(Collectors.toMap(Person::getClassName, Person::getStudentName,(key1,key2)->key1));
- 重复时将之前的value 和现在的value拼接或相加起来;????????
Map<String, String> map = list.stream().collect(Collectors.toMap(Person::getClassName, Person::getStudentName,(key1,key2)->key1+", "+key2));
Map<String, List<String>> map = list.stream().
collect(Collectors.toMap(Person::getClassName, s -> {
List<String> studentNameList = new ArrayList<>();
studentNameList.add(s.getStudentName());
return studentNameList;
}, (List<String> value1, List<String> value2) -> {
value1.addAll(value2);
return value1;
}));
System.out.println(map);
|