用Optional Encapsulate 可能係null既Class,提高Readaibility,Robustness(執行過程中處理錯誤,以及演算法在遭遇輸入、運算等異常時維持正常運作的能力)
避免空指標異常(NullPointerException)
可以避免空指標異常,提高程式碼的健全性和可讀性。
可以減少明確的空值檢查和 null 的使用,使程式碼更簡潔優雅。
可以利用函數式程式設計的特性,實現更靈活和高效的邏輯處理。
可提高程式碼的可測試性,方便進行單元測試和整合測試。
Optional
- Create Optional
- of(T value)=>Create non-null object
- empty()=>Create null object
- // create一個null 的 Optional object
Optional<String> empty = Optional.empty();
- ofNullable(T value)=>Create maybe null object
- // Create一个可能係 null的 Optional object
Optional<String> name = Optional.ofNullable("Hello");
- Optional Method
- isEmpty()=>判斷係唔係null,return boolean
- isPresent()=>判斷object有冇value
- get()=>if object is not null , return value / NoSuchElementException
- // 使用 isPresent 和 get 方法
Optional<String> name = Optional.ofNullable("tom");
if (name.isPresent()) {
System.out.println("Hello, " + name.get());
} else {
System.out.println("Name is not available");
}
// 輸出:Hello tom
- ifPresent(Consumer<? super T> action)=>object is not null,執行Consumer動作/乜都唔做
- // 使用 ifPresent(Consumer<? super T> action)
Optional<String> name = Optional.ofNullable("tom");
name.ifPresent(s -> {
System.out.println("Hello, " + name.get());
});
// 輸出:Hello tom
- ofElse(T other)=>
- // 使用 orElse(T other)
Optional<String> name = Optional.ofNullable(null);
String greeting = "Hello, " + name.orElse("Guest");
System.out.println(greeting);
// 輸出:Hello Guest
- orElseGet(Supplier<? extends T>supplier)
- // 使用 orElseGet(Supplier<? extends T> supplier)
Optional<String> name = Optional.ofNullable(null);
String greeting = "Hello, " + name.orElseGet(() -> "Guset");
System.out.println(greeting);
// 輸出:Hello Guset
- orElseThrow(Supplier<? extends X>exceptionSupplier)
- // 使用 orElseThrow(Supplier<? extends X> exceptionSupplier)
Optional<String> name = Optional.ofNullable(null);
String greeting = "Hello, " + name.orElseThrow(() -> new NullPointerException("null"));
// 抛出 java.lang.NullPointerException: null 异常
- map(Function<? super T,? extends U> mapper)
- // 使用 map(Function<? super T,? extends U> mapper)
Optional<String> name = Optional.ofNullable("tom");
String greeting = "Hello, " + name.map(s -> s.toUpperCase()).get();
System.out.println(greeting);
// 輸出:Hello TOM
- flatMap(Function<? super T,? extends Optional<? extends U>> mapper)
- // 使用 flatMap(Function<? super T,Optional<U>> mapper)
Optional<String> name = Optional.ofNullable("tom");
String greeting = name.flatMap(s -> Optional.of("Hello " + s)).get();
System.out.println(greeting);
// 輸出:Hello tom
- filter(Predicate<? super T>predicate)
- // filter(Predicate<? super T> predicate)
Optional<String> name = Optional.ofNullable("tom");
String greeting = "Hello " + name.filter(s -> !s.isEmpty()).get();
System.out.println(greeting);
// 輸出:Hello tom
- Java9 新增
- isPresentOrElse(Consumer<? super T>action,Runnable emptyAction)
- Optional<Integer> optional = Optional.of(1);
optional.ifPresentOrElse(
x -> System.out.println("Value: " + x),
() -> System.out.println("Not Present.")
);
optional = Optional.empty();
optional.ifPresentOrElse(
x -> System.out.println("Value: " + x),
() -> System.out.println("Not Present.")
);
// 輸出:Value: 1
// 輸出:Not Present.
- or(Supplier<? extends Optional<? extends T>> supplier)
- Optional<String> optional = Optional.of("Hello ");
Supplier<Optional<String>> supplier = () -> Optional.of("tom");
optional = optional.or(supplier);
optional.ifPresent(x -> System.out.println(x));
optional = Optional.empty();
optional = optional.or(supplier);
optional.ifPresent(x -> System.out.println(x));
// 輸出:Hello
// 輸出:tom
- stream()
- List<Optional<String>> list = Arrays.asList(
Optional.empty(),
Optional.of("A"),
Optional.empty(),
Optional.of("B")
);
// 使用 stream() filter List,只保留non null
List<String> filteredList = list.stream()
.flatMap(Optional::stream)
.collect(Collectors.toList());
System.out.println(filteredList);
// 輸出 [A, B]
graph TD;A[Java Basics] –> B[Primitives and Wrapper Classes]B –> B1[Primitive Types]B1 –> B1_1[byte]B1 –> B1_2[short]B1 –> B1_3[int]B1 –> B1_4[long]B1 –> B1_5[float]B1 –> B1_6[double]B1 –> B1_7[char]B1 –> B1_8[boolean]B –> B2[Wrapper Classes]B2 –> B2_1[Byte]B2 –> B2_2[Short]B2 –> B2_3[Integer]B2 –> B2_4[Long]B2 –> B2_5[Float]B2 –> B2_6[Double]B2 –> B2_7[Character]B2 –> B2_8[Boolean]
Jul 17, 2024https://codewave16.github.io/interviewQuestion/
Jun 19, 2024CREATE TABLE [IF NOT EXISTS] NAME()
Jun 12, 202430天Web開發入門課程
Apr 9, 2024or
By clicking below, you agree to our terms of service.
New to HackMD? Sign up