20230619 java.util.Optional

发布时间 2023-08-22 17:42:50作者: 流星<。)#)))≦

介绍

  • java.util.Optional
  • 类声明
@jdk.internal.ValueBased
public final class Optional<T>
  • 包装一个可能为 null 的值
  • 只有在正确使用的情况下才会更安全
  • 对应基本类型类:OptionalInt, OptionalLong, OptionalDouble

API

static

创建 Optional

  • empty
  • of
  • ofNullable

public

  • get

    • 值为 null 时,抛出 NoSuchElementException
  • isPresent

    • 判断值不为 null
  • isEmpty

    • isPresent
    • 判断值为 null
  • ifPresent

    • void ifPresent(Consumer<? super T> action)
    • 如果值不为 null ,传递给 action
  • ifPresentOrElse

    • ifPresent
  • filter

  • map

  • flatMap

  • stream

    • Stream<T> stream()
    • 值为 null 时,返回空流,否则返回包含一个值的流
  • or

  • orElse

  • orElseGet

  • orElseThrow