普通对象
集合对象
首先下面代码中的List放入了很多Person对象,其中有的对象是null的,如果不加校验调用Person的getXXX()方法肯定会报空指针错误,一般我们采取的方案就是加上if判断:
public class DemoUtils {
public static void main(String[] args) {
List<Person> personList = new ArrayList<>();
personList.add(new Person());
personList.add(null);
personList.add(new Person("小明",10));
personList.add(new Person("小红",12));
for (Person person : personList) {
//if判空逻辑
if (person != null) {
System.out.println(person.getName());
System.out.println(person.getAge());
}
}
}
static class Person {
private String name;
private int age;
}
}
利用Stream API 中的 filter将队列中的空对象过滤掉,filter(Objects::nonNull)的意思是,list中的每个元素执行Objects的nonNull()方法,返回false的元素被过滤掉,保留返回true的元素。
public static void main(String[] args) {
List<Person> personList = new ArrayList<>();
personList.add(new Person());
personList.add(null);
personList.add(new Person("小明",10));
personList.add(new Person("小红",12));
personList.stream().filter(Objects::nonNull).forEach(person->{
System.out.println(person.getName());
System.out.println(person.getAge());
});
}
示例中的personList本身也可能会null,如果业务逻辑中要求personList为null时打日志报警,可以用Optional优雅的实现:
public static void main(String[] args) {
List<Person> personList = new ArrayList<>();
personList.add(new Person());
personList.add(null);
personList.add(new Person("小明", 10));
personList.add(new Person("小红", 12));
Optional.ofNullable(personList).orElseGet(() -> {
logger.info("personList为null!");
return new ArrayList<>();
}).stream().filter(Objects::nonNull).forEach(person -> {
System.out.println(person.getName());
System.out.println(person.getAge());
});
}