Optional的简单使用

public class OptionalDemo { public static void main(String[] args) { Insurance pacificOcean = new Insurance("太平洋", 3456d); Insurance life = new Insurance("人寿", 2456d); Car bmw = new Car("BMW", 320000d, null); Car audi = new Car("AUDI", 350000d, life); User lucy = new User("Lucy", bmw); User lily = new User("Lily", null); // 1、Optional.of()只能接受非空值, Optional o = Optional.of(null); // 2、Lily如果没有车子,默认给她一个audi Car car = Optional.ofNullable(lily.getCar()).orElse(audi); System.out.println(car); // Lucy有一辆BMW车子 car = Optional.ofNullable(lucy.getCar()).orElse(bmw); System.out.println(car); // 3、如果 Optional 中有值,则对该值调用 consumer.accept,否则什么也不做。 Optional car1 = Optional.ofNullable(lily.getCar()); if (car1.isPresent()) { car1.ifPresent(item -> System.out.println(item.getInsurance())); } else { System.out.println("Lily没有车子"); } car1 = Optional.ofNullable(lucy.getCar()); if (car1.isPresent()) { car1.ifPresent(item -> System.out.println(item.getInsurance())); } else { System.out.println("Lucy没有车子"); }// 4、Lily如果没有车子,现在给她指定一辆别克 car = Optional.ofNullable(lily.getCar()).orElseGet(() -> new Car("BUICK", 230000d, pacificOcean)); System.out.println(car); // 5、Lily没有车子,抱怨一下 car = Optional.ofNullable(lily.getCar()).orElseThrow(() -> new RuntimeException("别人都有车子,我没有车子")); System.out.println(car); // 6、如果当前 Optional 为 Optional.empty,则依旧返回 Optional.empty;否则返回一个新的 Optional String temp = Optional.ofNullable(lucy).map(User::getCar).map(Car::getInsurance).map(Insurance::getCompany).orElse("没有保险"); System.out.println(temp); // 7、flatMap 方法与 map 方法的区别在于,map 方法参数中的函数 mapper 输出的是值,然后 map 方法会使用 Optional.ofNullable 将其包装为 Optional temp = Optional.ofNullable(lucy) .flatMap(item -> Optional.ofNullable(item.getCar())) .flatMap(item -> Optional.ofNullable(item.getInsurance())) .flatMap(item -> Optional.ofNullable(item.getCompany())) .orElse("我车都没得,哪里有保险"); System.out.println(temp); } }@Data @AllArgsConstructor class User { private String name; private Car car; }@Data @AllArgsConstructor class Car { private String brand; private double price; private Insurance insurance; }@Data @AllArgsConstructor class Insurance { private String company; private double cost; }
【Optional的简单使用】

    推荐阅读