Skip to content

Instantly share code, notes, and snippets.

@Jian-Min-Huang
Last active December 18, 2022 15:31
Show Gist options
  • Save Jian-Min-Huang/6547c6c1915619481d609c15753ccfaf to your computer and use it in GitHub Desktop.
Save Jian-Min-Huang/6547c6c1915619481d609c15753ccfaf to your computer and use it in GitHub Desktop.
Optional Note Part1
public class OptSample {
public void demoOpt() {
String requestBody = sendPost();
// 頭部
// of -> 確定不為 Null 的值
// ofNullable -> 可能為 Null 的值
Optional.of(requestBody).orElse("Empty Body");
Optional.ofNullable(requestBody).orElse("Empty Body");
// 身體
// filter -> if 的效果
// map -> invoke function 的效果
// flatMap -> 傳入值是是 Optional<T> 的 map
// or -> 有點像前三者的合體
// stream -> 轉乘 Java Stream 類別
Optional.of(requestBody).filter(v -> v.isBlank()).orElse("Empty Body");
Optional.of(requestBody).map(v -> v.toUpperCase()).orElse("Empty Body");
Optional.of(requestBody).flatMap(v -> optMapper(v)).orElse("Empty Body");
Optional.of(requestBody).or(() -> optMapper("Empty Supplier")).orElse("Empty Body");
Optional.of(requestBody).stream();
// 尾巴
// ifPresent -> 如果不為 Null 就執行 Consumer
// ifPresentOrElse -> 如果不為 Null 就執行 Consumer 否則呼叫 Supplier
// orElse -> 如果不為 Null 就回傳容器內的值否則回傳預設值
// orElseGet -> 如果不為 Null 就回傳容器內的值否則呼叫 Supplier
// orElseThrow -> 如果不為 Null 就回傳容器內的值否則拋出 Exception
Optional.ofNullable(requestBody).ifPresent(v -> System.out.println(v));
Optional.ofNullable(requestBody).ifPresentOrElse(v -> System.out.println(v), () -> System.out.println("else action"));
Optional.ofNullable(requestBody).orElse("Empty Body");
Optional.ofNullable(requestBody).orElseGet(() -> {return "Empty Body";});
Optional.ofNullable(requestBody).orElseThrow(() -> new RuntimeException("Empty Body"));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment