是否有任何简单的方法来减少代码行以使用 Optional
作为以下代码的替代来打印最内层的非 null
对象。我觉得我们现在必须编写更多代码行来避免空值检查。
在 Java 8 中有什么简单的方法可以使这段代码变得简短而有趣吗?
import java.util.Optional;
public class OptionalInnerStruct {
public static void main(String[] args) {
// creepy initialization step, dont worry
Employee employee = new Employee();
employee.setHuman(Optional.empty());
// with optional
Optional<Human> optionalHuman = employee.getHuman();
if (optionalHuman.isPresent()) {
Human human = optionalHuman.get();
Optional<Male> optionalMale = human.getMale();
if (optionalMale.isPresent()) {
Male male = optionalMale.get();
Optional<Integer> optionalAge = male.getAge();
if (optionalAge.isPresent()) {
System.out.println("I discovered the variable finally " + optionalAge.get());
}
}
}
// without optional in picture, it will be something like:
/*if(null! = employee.getHuman() && null!= employee.getHuman().getMale() && null! = employee.getHuman().getMale().getAge()) {
System.out.println("So easy to find variable " + employee.getHuman().getMale().getAge());
}*/
}
static class Employee {
Optional<Human> human;
public Optional<Human> getHuman() {
return human;
}
public void setHuman(Optional<Human> human) {
this.human = human;
}
}
class Human {
Optional<Male> male;
public Optional<Male> getMale() {
return male;
}
public void setMale(Optional<Male> male) {
this.male = male;
}
}
class Male {
Optional<Integer> age;
public Optional<Integer> getAge() {
return age;
}
public void setAge(Optional<Integer> age) {
this.age = age;
}
}
}
最佳答案
您可以使用 Optional.flatMap
这里
employee.getHuman()
.flatMap(Human::getMale)
.flatMap(Male::getAge)
.ifPresent(age -> System.out.println("I discovered the variable finally " + age);
关于Java 8 可选——如何处理嵌套的对象结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50186257/