Student:
@Data
@AllArgsConstructor
public class Student {
private String name;
private Integer age;
private Integer score;
}
把list转成map
List<Student> students = List.of(
new Student("zhangsan", 20, 80),
new Student("zhangsan", 20, 81),
new Student("lisi", 21, 82),
new Student("wangwu", 20, 83),
new Student("zhaoliu", 20, 83)
);
Map<String, Integer> scoreMap = students.stream()
.collect(Collectors.toMap(
Student::getName,
Student::getScore
));
System.out.println("scoreMap = " + scoreMap); // 报 `java.lang.IllegalStateException: Duplicate key zhangsan (attempted merging values 80 and 81)`
遇重复key时,两个value就会导致报错。
遇到list里有重复key时报错的解决方法:
// 遇重复key, 取第一个value
Map<String, Integer> scoreMap2 = students.stream()
.collect(Collectors.toMap(
Student::getName,
Student::getScore,
(score1, score2) -> score1
));
System.out.println("scoreMap2 = " + scoreMap2);
运行正常,打印结果:scoreMap2 = {lisi=82, zhaoliu=83, zhangsan=80, wangwu=83}
扩展:如果想让map有序,即map key序列与list一致,如何实现?
如下:
// 遇重复key, 取第一个value,并按list里的序列生成map
Map<String, Integer> scoreMap3 = students.stream()
.collect(Collectors.toMap(
Student::getName,
Student::getScore,
(score1, score2) -> score1,
LinkedHashMap::new
));
System.out.println("scoreMap3 = " + scoreMap3);
打印结果:scoreMap3 = {zhangsan=80, lisi=82, wangwu=83, zhaoliu=83}