在Optional/Stream的中间操作中如何处理NPE?

huangapple go评论57阅读模式
英文:

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();

在这里处理空指针异常的最佳方法是使用OptionalofNullable方法来包装可能为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);

huangapple
  • 本文由 发表于 2020年8月7日 08:56:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/63293742.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定