
文章插图
2.3.3 值获取方法1)源码
public T get() {if (value =https://www.huyubaike.com/biancheng/= null) {throw new NoSuchElementException("No value present");}return value;}
3)测试代码
public static void main(String[] args) {Integer value1 = null;Integer value2 = 1;Optional<Integer> optional1 = Optional.ofNullable(value1);Optional<Integer> optional2 = Optional.of(value2);try {Integer result=optional1.get();System.out.println("optional1的值是:"+result);}catch (Exception e){System.out.println("optional1的值获取失败,原因:"+e.getMessage());}try {Integer result=optional2.get();System.out.println("optional2的值是:"+result);}catch (Exception e){System.out.println("optional2的值获取失败,原因:"+e.getMessage());}}

文章插图
2.3.4 判断方法1)源码
public boolean isPresent() {return value != null;}public void ifPresent(Consumer<? super T> consumer) {if (value != null)consumer.accept(value);}public T orElse(T other) {return value != null ? value : other;}public T orElseGet(Supplier<? extends T> other) {return value != null ? value : other.get();}public <X extends Throwable> T orElseThrow(Supplier<? extends X> exceptionSupplier) throws X {if (value != null) {return value;} else {throw exceptionSupplier.get();}}
- isPresent(): 判断optional是否为空,如果空则返回false,否则返回true
- ifPresent(Consumer c): 如果optional不为空,则将optional中的对象传给Comsumer函数
- orElse(T other): 如果optional不为空,则返回optional中的对象;如果为null,则返回 other 这个对象 。
- orElseGet(Supplier other): 如果optional不为空,则返回optional中的对象;如果为null,否则调用其他函数并返回调用的结果
- orElseThrow(Supplier exception): 如果optional不为空,则返回optional中的对象;如果为null,则抛出Supplier函数生成的异常
public static void main(String[] args) {Integer value1 = null;Integer value2 = 1;Optional<Integer> optional1 = Optional.ofNullable(value1);Optional<Integer> optional2 = Optional.of(value2);try {if(optional1.isPresent()){System.out.println("optional1的isPresent结果不为空");}else{System.out.println("optional1的isPresent结果为空");}}catch (Exception e){System.out.println("optional1的isPresent判空失败,原因:"+e.getMessage());}try {if(optional2.isPresent()){System.out.println("optional2的isPresent结果不为空");}else{System.out.println("optional2的isPresent结果为空");}}catch (Exception e){System.out.println("optional2的isPresent判空失败,原因:"+e.getMessage());}optional1.ifPresent(t->{int i =t+1;System.out.println("optional1处理后的值是"+i);});optional2.ifPresent(t->{int i =t+1;System.out.println("optional2处理后的值是"+i);});Integer value3 = 2;Integer result = optional1.orElse(value3);System.out.println("optional1执行orElse处理后的值是"+result);推荐阅读
- Go 源码解读|如何用好 errors 库的 errors.Is 与 errors.As() 方法
- Optional 常用方法总结
- 92年属猴人注定的婚姻解析,要注意什么
- 手相女右手解析 教你如何看懂女人的手相
- 四种假断掌图片 手掌纹路帮解析
- 专家解析 耳再造手术大概多少钱
- 手相女右手解析什么是岛纹,跟纹路形状有关,会有一些不利影响
- 哈尔的移动城堡解析影评 哈尔的移动城堡解析?
- 住房贷款专项扣除标准是多少?住房贷款专项扣除全解析来了
- 主板的南北桥解析知识
