import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
class Student {
private String name;
private int score;
public Student(String name, int score) {
this.name = name;
this.score = score;
}
public String getName() {
return name;
}
public int getScore() {
return score;
}
}
public class Main {
public static void main(String[] args) {
List<Student> studentList = new ArrayList<>();
studentList.add(new Student("张三", 85));
studentList.add(new Student("李四", 90));
List<String> resultList = studentList.stream()
.map(student -> student.getName() + ":" + student.getScore())
.collect(Collectors.toList());
System.out.println(resultList);
}
}
空指针异常原因及避免方法
- 原因:
- 在
map
转换过程中,如果Student
对象为null
,或者Student
对象中的name
属性为null
,就会出现空指针异常。例如,如果studentList
中有null
元素,执行student.getName()
时就会抛出空指针异常;如果Student
对象的name
属性未正确初始化,为null
,执行student.getName() + ":" + student.getScore()
时也会抛出空指针异常。
- 避免方法:
- 过滤
null
元素:在使用map
方法之前,先使用filter
方法过滤掉List<Student>
中的null
元素。例如:
List<String> resultList = studentList.stream()
.filter(student -> student != null)
.map(student -> student.getName() + ":" + student.getScore())
.collect(Collectors.toList());
- 增加空值检查:在
map
方法中对可能为空的属性增加空值检查。例如:
List<String> resultList = studentList.stream()
.map(student -> {
if (student == null) {
return "未知:0";
}
String name = student.getName();
if (name == null) {
name = "未知";
}
return name + ":" + student.getScore();
})
.collect(Collectors.toList());