Optional
1、实体类
/** * 对象 * User(id=null, name=null, age=null, address=null) * Address(x=null, y=null, location=null) */
2、ifPresent
/** * 如果user不为空则获取Address对象,过滤location属性空值,如果有值则打印user对象 */ Optional.ofNullable(user) .map(User::getAddress) .filter(entity->entity.getLocation()!=null) .ifPresent(consumer->{ System.out.println(user); }); Address address2= new Address(); address2.setLocation("上海");
3、orElse
/** * 如果entity里面的getLocation不为空则取entity对象值,否则取address2对象 不管有没有值orElse都会执行 */ Address address11 = Optional.ofNullable(user) .map(User::getAddress) .filter(entity -> entity.getLocation() != null) .orElse(address2);
4、orElseThrow
/** * 如果entity里面的getLocation不为空则取entity对象值,否则取抛出异常 */ Address address22 = Optional.ofNullable(user) .map(User::getAddress) .filter(entity -> entity.getLocation() != null) .orElseThrow(()->new RuntimeException("错误"));
5、orElseGet
/** * 如果entity里面的getLocation不为空则取entity对象值,否则取address2对象 与orElse的区别就是orElseGet在没有值的情况下才会执行,有值则不执行orElseGet */ Address address33 = Optional.ofNullable(user) .map(User::getAddress) .filter(entity -> entity.getLocation() != null) .orElseGet(()->new Address());