本文主要介绍Java 8
的Optional
的简单使用
1
2
3
4
5
6
7
|
publicclassAddress {
private String province;
private String city;
}
|
相关代码托管在java8_demo
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
publicvoidemptyTest() {
// 声明一个空的Optional对象
Optional
nameOptional = Optional.empty();
// java.util.NoSuchElementException: No value present
nameOptional.get();
}
publicvoidofNullTest() {
// 依据实例创建Optional对象
Optional.of(
new Address("Guangdong","Zhongshan"));
// Optional.ofNullable(null)返回Optional.empty()
assertEquals(Optional.empty(), Optional.ofNullable(
null));
// java.lang.NullPointerException
Optional.of(
null);
}
|
Stream.map
的定义:
Optional.map
的定义: Optional map(Function super T, ? extends U> mapper)
上面两者定义非常类似,Optional
可看成最多包含一个元素
的Stream
1
2
3
4
5
6
7
8
9
10
11
|
publicvoidmapTest() {
String province =
"Guangdong";
String city =
"Zhongshan";
Optional
addressOptional = Optional.of(new Address(province, city));
// mapper : Address -> String
// Optional-> Optional
Optional
assertTrue(stringOptional.isPresent());
assertEquals(city, stringOptional.get());
}
|
Stream.flatMap
的定义:
Optional.flatMap
的定义: Optional flatMap(Function super T, Optional> mapper)
1
2
3
4
5
6
7
8
9
10
11
12
|
publicvoidflatmapTest() {
String province =
"Guangdong";
String city =
"Zhongshan";
Optional
addressOptional = Optional.of(new Address(province, city));
// 对于 mapper 为 T -> Optional时,调用Optional.map,生成的是Optional
Optional
// 对于 mapper 为 T -> Optional时,调用Optional.map,生成的是Optional,被扁平化
Optional
assertTrue(stringOptional.isPresent());
assertEquals(city, stringOptional.get());
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
publicvoiddereferenceTest() {
// get:最简单 + 最不安全
Address address = addressOptional.get();
assertNotNull(address);
address =
null;
Optional
emptyAddressOptional = Optional.ofNullable(address);
String defaultValue =
"Unknown";
// orElse:设置默认值
Address elseAddress = emptyAddressOptional.orElse(
new Address(defaultValue, defaultValue));
assertEquals(defaultValue, elseAddress.getProvince());
assertEquals(defaultValue, elseAddress.getCity());
// orElseGet:orElse的延迟调用版本
Address elseGetAddress = emptyAddressOptional.orElseGet(Address::
new);
assertNull(elseGetAddress.getProvince());
assertNull(elseGetAddress.getCity());
// ifPresent:存在值则运行consumer,否则不进行任何操作
emptyAddressOptional.ifPresent(System.out::println);
// orElseThrow:不存在时,抛出异常
emptyAddressOptional.orElseThrow(UnsupportedOperationException::
new);
}
|
1
2
3
4
|
publicvoidfilterTest() {
assertTrue(addressOptional.filter(address -> address.getCity().contains(
"Z")).isPresent());
}
|
OptionalInt
、OptionalLong
、OptionalDouble
最多只有一个
元素,并没有像StreamInt
那样相对于Stream
有性能优势
不支持map
、flatmap
、filter
以上是Java 8——Optional的详细内容。更多信息请关注PHP中文网其他相关文章!