本文主要介紹Java 8
的 Optional
的簡單使用
1
2
3
4
#5
6
7
|
#public class Address {
#private String province; #private String city;
| }
#of + ofNullable
1
#2
3 ##4##5
6
7
8
9
#10
#11
#12
13
14
15
16
17
18
|
#public void emptyTest() {
// 宣告一個空的Optional物件
Optional nameOptional = Optional.empty();
// java.util.NoSuchElementException: No value present
nameOptional.get(); ##}# #@Test(expected = NullPointerException.class)
#public void ofNullTest() {
// 依據實例建立Optional物件
Optional.of(new Address("Guangdong", "Zhongshan"));
// Optional.ofNullable(null)回傳Optional.empty()
assertEquals(Optional.empty(), Optional.ofNullable(null));
// java.lang.NullPointerException Optional.of(null);
}
|
1
1
2
3
4
5
6
7
| 8
9 1011#@Test
##public void mapTest () {
#String province = "Guangdong";
##String city = "Zhongshan";
Optional addressOptional = Optional.of(
new Address(province, city));
// mapper : Address -> String
// Optional -> Optional |
assertEquals(city, stringOptional。 ##}
#Stream.flatMap
的定義:
##Optional.flatMap
##Optional.flatMap 的定義: Optional flatMap(Function super T, Optional> mapper)
|
12#3##4##5#6
78
910
1112
@Test
public void flatmapTest##() {
String province = | "Guangdong";
1
2
3 ##4 # #5678910##11
12
13
14
15
16
17
18
# 19
| 20
2122
#23#24#25#26
@Test(expected = UnsupportedOperationException.class)
public void dereferenceTest () {
## // 取得:最簡單+ 最不安全
位址address = 位址可選.get(); assertNotNull(address);null;
#可選; emptyAddressOptional =Optional.ofNullable(address); String defaultValue = "Unknown";
// orElse:設定預設值
##位址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()); | emptyAddressOptional.ifPresent(System.out::println) ;
new); ##} 過濾器 |
##1
234##@測試
# #公共void filterTest() {
|
##}基礎類型+ 可選
##OptionalInt、
OptionalLong、
OptionalDouble
以上是Java 8——可選的詳細內容。更多資訊請關注PHP中文網其他相關文章!