简体   繁体   中英

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.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?

Person person = new Person();
Optional.ofNullable(person.getAddress())
        .flatMap(p -> Optional.of(p.getCity()))
        .flatMap(c -> Optional.of(c.getName()))
        .orElseThrow(NullPointerException::new);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM