问题一: Exception in thread "main" java.lang.NullPointerException: element cannot be mapped to a null key
原因:当使用stream流进行分组,分组的 key 为 null 则报上述错误
@Data
class Studet{
private int id;
private String name;
public Studet() {
}
public Studet(int id) {
this.id = id;
}
}
Map<Integer, List<Studet>> studentMap = Lists.newArrayList(new Studet(), new Studet(1), new Studet(2))
.stream().collect(Collectors.groupingBy(Studet::getId));
问题二:Exception in thread "main" java.lang.IllegalStateException: Duplicate key 2
原因:当使用stream流转map时,当前集合中作为key的属性相同时则报上述错误。
@Data
class Studet{
private int id;
private String name;
public Studet() {
}
public Studet(int id) {
this.id = id;
}
public Studet(int id, String name) {
this.id = id;
this.name = name;
}
}
Map<Integer, String> studentMap = Lists.newArrayList( new Studet(1,"1"), new Studet(2,"2"), new Studet(2,"2"))
.stream().collect(Collectors.toMap(Studet::getId, Studet::getName));
问题三:Exception in thread "main" java.lang.NullPointerException
原因:当使用stream流转map时,作为map的value也不可以为null,否则报上述空指针问题
@Data
static class Student{
private int id;
private String name;
}
public static void main(String[] args) {
Student student1 = new Student();
student1.setId(0);
Student student2 = new Student();
student2.setId(1);
Student student3 = new Student();
student3.setId(2);
List<Student> students = new ArrayList<>();
students.add(student1);
students.add(student2);
students.add(student3);
Map<Integer, String> studentMap = students.stream().collect(Collectors.toMap(Student::getId, Student::getName));
}
总结:当使用stream流生成map映射对象时,作为key和作为value的属性都不能为空