英文:
How to handle NPE in the intermediate operations of Optional/Stream?
问题
public class Person {
private String name;
private Address address;
}
public class Address {
private City city;
}
public class City {
private String name;
}
Optional.ofNullable(Person::getAddress)
.map(address -> Optional.ofNullable(address.getCity())
.map(City::getName)
.orElse(null))
.orElseThrow();
在这里处理空指针异常的最佳方法是使用Optional
的ofNullable
方法来包装可能为null的值。首先,使用ofNullable
包装getAddress
方法的调用,然后在第一个.map
中对address
对象进行处理。在内部的Lambda表达式中,再次使用ofNullable
来包装getCity
方法的调用,然后使用第二个.map
来处理City
对象的名字。最后,使用orElse(null)
来处理整个链中的空值,然后调用orElseThrow
来抛出异常。
英文:
public class Person {
private String name;
private Address address;
}
public class Address {
private City city
}
public class City {
private String name;
}
Optional.of(Person::getAddress).map(Address::getCity).map(City::getName).orElseThrow();
The middle two .map
may throw NPE because getAddress
and getCity
may return null. What's the best approach to handle NPE here?
答案1
得分: 2
Person person = new Person();
Optional.ofNullable(person.getAddress())
.flatMap(p -> Optional.of(p.getCity()))
.flatMap(c -> Optional.of(c.getName()))
.orElseThrow(NullPointerException::new);
英文:
Person person = new Person();
Optional.ofNullable(person.getAddress())
.flatMap(p -> Optional.of(p.getCity()))
.flatMap(c -> Optional.of(c.getName()))
.orElseThrow(NullPointerException::new);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论