是否有减少的代码行打印使用null
作为替代下面的代码最里面的不Optional
对象中的任何简单的方法。我感觉我们必须编写更多的代码,避免无效检查了。
有没有简单的方法来使此代码短暂的甜蜜在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);