🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
> ### Optional容器 使用Optional容器可以快速的定位NPE,并且在一定程度上可以减少对参数非空检验的代码量。 ``` /** * Optional.of(T t); // 创建一个Optional实例 * Optional.empty(); // 创建一个空的Optional实例 * Optional.ofNullable(T t); // 若T不为null,创建一个Optional实例,否则创建一个空实例 * isPresent(); // 判断是够包含值 * orElse(T t); //如果调用对象包含值,返回该值,否则返回T * orElseGet(Supplier s); // 如果调用对象包含值,返回该值,否则返回s中获取的值 * map(Function f): // 如果有值对其处理,并返回处理后的Optional,否则返回Optional.empty(); * flatMap(Function mapper);// 与map类似。返回值是Optional * */ @Test public void test() { Optional<Employee> of = Optional.of(new Employee("zhangsan", 12)); System.out.println(of.get()); // NEP Optional<Object> of2 = Optional.of(null); Optional<Object> empty = Optional.empty(); } @Test public void test2() { Optional<Object> empty = Optional.empty(); System.out.println(empty); // No value present System.out.println(empty.get()); } @Test public void test3() { Optional<Employee> ofNullable = Optional.ofNullable(new Employee("zhangsan", 12)); System.out.println(ofNullable); System.out.println(ofNullable.isPresent()); System.out.println(ofNullable.orElse(new Employee("je", 12))); Optional<Object> ofNullable2 = Optional.ofNullable(null); System.out.println(ofNullable2); System.out.println(ofNullable2.isPresent()); System.out.println(ofNullable2.orElse(new Employee("je", 12))); System.out.println(ofNullable2.orElse(null)); } @Test public void test4() { Optional<Employee> ofNullable = Optional.ofNullable(new Employee("zhangsan", 12)); System.out.println(ofNullable.orElseGet(()-> new Employee())); Optional<Object> ofNullable2 = Optional.ofNullable(null); System.out.println(ofNullable2.orElseGet(()-> new Employee())); } @Test public void test5() { Optional<Employee> ofNullable = Optional.ofNullable(new Employee("zhangsan", 12)); System.out.println(ofNullable.map(e->e.getEmployeeName())); System.out.print(ofNullable.flatMap(e->Optional.of(e.getEmployeeName()))); } ``` ***** 原文链接:https://blog.csdn.net/qq_29411737/article/details/80835658