jdk8中的方法

  • empty
  • of
  • ofNullable
  • get
  • isPresent
  • ifPresent
  • filter
  • map
  • flatMap
  • orElse
  • orElseGet
  • orElseThrow

    常用方法

  • ofNullable

  • of
  • isPresent
  • empty
  • get
  • orElse
  • orElseThrow

    ofNullable

  • 允许参数为null

    • 但是不能get(),会报错, 必须先判断是否为空(ifPresent) ```java String strNull = null; Optional ofNull = Optional.ofNullable(strNull); /** System.out.println(“ofNull.get() = “ + ofNull.get());

Exception in thread “main” java.util.NoSuchElementException: No value present at java.util.Optional.get(Optional.java:135) at io.tn.test.test.OptionalTest.main(OptionalTest.java:20) */

  1. <a name="gCwRd"></a>
  2. # of
  3. - 不允许参数为null,直接报错
  4. - null ≠ 空类型
  5. - 参数可以为空 eg: `String str = new String()`
  6. ```java
  7. String strNull = null;
  8. Optional<String> of = Optional.of(strNull);
  9. /*****************
  10. Exception in thread "main" java.lang.NullPointerException
  11. at java.util.Objects.requireNonNull(Objects.java:203)
  12. at java.util.Optional.<init>(Optional.java:96)
  13. at java.util.Optional.of(Optional.java:108)
  14. at io.tn.test.test.OptionalTest.main(OptionalTest.java:18)
  15. ************************/

isPresent

  • 指挥判断 null 不会判断对象是否为空

    • null ≠ 空类型
      1. public boolean isPresent() {
      2. return value != null;
      3. }

      empty

  • 返回空对象

    • 如果对象等于null就 new 个空对象;
      1. public static<T> Optional<T> empty() {
      2. @SuppressWarnings("unchecked")
      3. Optional<T> t = (Optional<T>) EMPTY;
      4. return t;
      5. }

      get

  • 获取对象中的值

    1. public static void main(String[] args) {
    2. String str = new String("23");
    3. Optional<String> of = Optional.of(str);
    4. System.out.println("of.get() = " + of.get());
    5. }
    6. /**********
    7. of.get() = 23
    8. ****/

    orElse

  • 如果参数为null则返回自定义的值

    1. String strNull = null;
    2. Optional<String> ofNull = Optional.ofNullable(strNull);
    3. System.out.println("orElse = " + ofNull.orElse("aa"));
    4. /**********
    5. orElse = aa
    6. ****/

    orElseThrow

  • 如果参数为null,直接手动抛出异常

    • null ≠ 空类型
      1. String strNull = null;
      2. String str = new String();
      3. // 为null 抛出异常
      4. Optional.ofNullable(str).orElseThrow(() -> new RuntimeException("这里报错了"));
      5. Optional.ofNullable(strNull).orElseThrow(() -> new RuntimeException("这里报错了"));