Optional类的使用 java8(附代码)
创始人
2024-11-21 17:35:11
0

🍰 个人主页:_小白不加班__
🍞文章有不合理的地方请各位大佬指正。
🍉文章不定期持续更新,如果我的文章对你有帮助➡️ 关注🙏🏻 点赞👍 收藏⭐️

文章目录

  • 一、什么是Optional?
  • 二、Optional常用api
      • 1.Optional.empty()
      • 2.Optional.of()
      • 3.Optional.ofNullable
      • 4.map
      • 5.flatMap
      • 6.ifPresent
      • 7.get
      • 8.orElse
      • 9.orElseGet
      • 10.orElseThrow
      • 11.filter`
  • 三、其他问题:
      • 1. Optional为何不可在 类中使用?
      • 2.为何避免使用 基础类型的Optional对象?

一、什么是Optional?

在 Java 8 中,Optional 是一个新的容器类,它被引入以更好地处理可能为 null 的值。
Optional 的主要目的是提供一种优雅的方式来避免空指针异常(NullPointerException)

二、Optional常用api

在这里插入图片描述

1.Optional.empty()

创建一个空的Optional对象
Optional optCar = Optional.empty();

2.Optional.of()

  1. 静态工厂方法,依据非空值创建对象
  2. 如果car是一个null,这段代码会立即抛出一个NullPointerException
    Optional optCar = Optional.of(car);

3.Optional.ofNullable

  1. 创建一个允许null值的Optional 对象
  2. 如果carnull,那么得到的Optional对象就是个空对象。
    Optional optCar = Optional.ofNullable(car);

4.map

  1. Optional 是一个容器类,用于封装可能为 null 的值。
  2. 不是一个传统的容器,如 List、Set、Map,只能存储一个值或者不存储任何值(即为空)
  3. Optional对象包含一个非空值,那么map方法会根据提供的函数,返回一个新的Optional对象,该对象包含转换后的值。
  4. 如果原始Optional对象为空,则返回一个空的Optional对象
// 保险 @Data public class Insurance {     private String name;     public String getName() {         return name;     } } @Test public void test1() {     Insurance insurance = new Insurance();     insurance.setName("阳光保险");     Optional name = Optional.ofNullable(insurance).map(Insurance::getName);     System.out.println(name);//阳光保险 } @Test public void test2() {     Insurance insurance = new Insurance();     Optional name = Optional.ofNullable(insurance).map(Insurance::getName);     System.out.println(name);//Optional.empty } 

5.flatMap

flatMap操作中使用 处理嵌套的 Optional 类型。
在这里插入图片描述

// 保险 @Data public class Insurance {     private String name;     public String getName() {         return name;     } } @Test public void test3() {     Optional optInsurance = Optional.ofNullable(new Insurance());     Optional name = optInsurance             .flatMap(insurance -> {                 System.out.println("insurance");//insurance                 return Optional.ofNullable(insurance.getName());             });     System.out.println(name);     /*     结果:     insurance     Optional.empty     */ } 

6.ifPresent

  1. 存在就执行使用该值的方法调用
@Test public void test4() {     Optional optInsurance = Optional.ofNullable(new Insurance());     optInsurance.ifPresent(insurance -> System.out.println(insurance)); } 

7.get

  1. 如果变量存在,它直接返回封装的变量值
  2. 否则就抛出一个NoSuchElementException异常
  3. 一般不用单独使用,除非确定值存在,不然失去了Optional的意义
@Test public void test4() {     Insurance insurance = new Insurance();     insurance.setName("保险");     Optional optInsurance = Optional.ofNullable(insurance);     System.out.println(optInsurance.get().getName());//保险    } 

8.orElse

在 Optional对象不包含值时提供一个默认值。

public String str() {    //模拟取值    return null; } /** * orElse */ @Test public void test5() {    String s = Optional.ofNullable(str()).orElse("default");    System.out.println(s);//default } 

9.orElseGet

public String str() {     //模拟取值     return null; } /***  * orElseGet  */ @Test public void test6() {     Supplier supplier = () -> {         return "default";     };     String s = Optional.ofNullable(str()).orElseGet(supplier);     System.out.println(s); // default } 

10.orElseThrow

指定Supplier抛出的异常

 public String strData() {         return null; } /**  * orElseThrow  */ @Test public void test7() {     try {         Optional.ofNullable(strData()).orElseThrow(RuntimeException::new);     } catch (RuntimeException e) {         System.out.println("RuntimeException");     }     //结果RuntimeException } 

11.filter`

是否满足谓词,满足返回包含该值的Optional对选,否则返回Optional.empty

@Test public void test8() {     Insurance insurance = new Insurance();     insurance.setName("A保险");     Optional optInsurance = Optional.ofNullable(insurance);     optInsurance             .filter((Insurance i) -> "A保险".equals(i.getName()))             .ifPresent(System.out::println); } 

三、其他问题:

1. Optional为何不可在 类中使用?

  • 由于Optional类设计时未实现 Serializable接口,无法序列化
    反例:
public class Person {  private Optional car;  public Optional getCar() { return car; } } 

2.为何避免使用 基础类型的Optional对象?

  • 除了Optional还提供 OptionalInt、OptionalLong、OptionalDouble 基础类型对象虽然提高了一些性能,但是灵活性大大较低
  • 基础类型Optional不支持map flatMap filter中间操作

参考:《java8 实战》

🍉文章不定期持续更新,如果我的文章对你有帮助➡️ 关注🙏🏻 点赞👍 收藏⭐️

相关内容

热门资讯

透视有挂!wepoker私人局... 透视有挂!wepoker私人局可以透视,wepoker透视版下载(好像真的是有挂)1、下载好wepo...
透视讲解!aapoker ai... 透视讲解!aapoker ai插件(透视)辅助插件工具(一直是真的有挂);1、操作简单,无需注册,只...
透视肯定(WPK)原来是真的有... 透视肯定(WPK)原来是真的有挂(透视)微扑克微乐辅助(必赢方法);1)微扑克微乐辅助辅助挂:进一步...
辅助透视!wepoker俱乐部... 辅助透视!wepoker俱乐部辅助器,wepoker私人局辅助挂(切实是真的有挂);1、下载好wep...
透视游戏!aapoker俱乐部... 透视游戏!aapoker俱乐部靠谱吗(透视)万能辅助器(一直有挂)aapoker俱乐部靠谱吗是一种具...
透视模拟器(WPK)总是是真的... 透视模拟器(WPK)总是是真的有挂(透视)微扑克微乐辅助(细节揭秘);1、金币登录送、破产送、升级送...
透视私人局!wepoker透视... 透视私人局!wepoker透视有用吗,wepokerh5破解(都是有挂)1、操作简单,无需注册,只需...
透视脚本!aapoker插件(... 透视脚本!aapoker插件(透视)透视方法(本来有挂);1、aapoker插件系统规律教程、aap...
透视玄学(WPK)确实是真的有... 透视玄学(WPK)确实是真的有挂(透视)wpk可以作弊吗(细节方法)1、不需要AI权限,帮助你快速的...
透视挂透视!wepoker亲友... 透视挂透视!wepoker亲友圈有用吗,wepoker私人局俱乐部怎么进(其实是有挂);1、完成we...