jdk8中的方法
- empty
- of
- ofNullable
- get
- isPresent
- ifPresent
- filter
- map
- flatMap
- orElse
- orElseGet
-
常用方法
ofNullable
- of
- isPresent
- empty
- get
- orElse
-
ofNullable
允许参数为null
- 但是不能get(),会报错, 必须先判断是否为空(ifPresent)
```java
String strNull = null;
Optional
ofNull = Optional.ofNullable(strNull); /** System.out.println(“ofNull.get() = “ + ofNull.get());
- 但是不能get(),会报错, 必须先判断是否为空(ifPresent)
```java
String strNull = null;
Optional
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) */
<a name="gCwRd"></a>
# of
- 不允许参数为null,直接报错
- null ≠ 空类型
- 参数可以为空 eg: `String str = new String()`
```java
String strNull = null;
Optional<String> of = Optional.of(strNull);
/*****************
Exception in thread "main" java.lang.NullPointerException
at java.util.Objects.requireNonNull(Objects.java:203)
at java.util.Optional.<init>(Optional.java:96)
at java.util.Optional.of(Optional.java:108)
at io.tn.test.test.OptionalTest.main(OptionalTest.java:18)
************************/
isPresent
指挥判断 null 不会判断对象是否为空
返回空对象
获取对象中的值
public static void main(String[] args) {
String str = new String("23");
Optional<String> of = Optional.of(str);
System.out.println("of.get() = " + of.get());
}
/**********
of.get() = 23
****/
orElse
如果参数为null则返回自定义的值
String strNull = null;
Optional<String> ofNull = Optional.ofNullable(strNull);
System.out.println("orElse = " + ofNull.orElse("aa"));
/**********
orElse = aa
****/
orElseThrow
如果参数为null,直接手动抛出异常
- null ≠ 空类型
String strNull = null;
String str = new String();
// 为null 抛出异常
Optional.ofNullable(str).orElseThrow(() -> new RuntimeException("这里报错了"));
Optional.ofNullable(strNull).orElseThrow(() -> new RuntimeException("这里报错了"));
- null ≠ 空类型