Created
August 13, 2022 02:10
-
-
Save wohhie/ca4906964aadd06d22af5f99d6aac8d5 to your computer and use it in GitHub Desktop.
JAVA OPTIONAL CLASS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static void main(String[] args) { | |
Optional<String> hello = Optional.ofNullable(null); | |
// 1. Optional Use: | |
// check value is present in hello | |
System.out.println(hello.isPresent()); | |
// check if hello(v) is empty | |
System.out.println(hello.isEmpty()); | |
// 2. orElse: if hello doesn't contain any value | |
// then $hello = world | |
String orElse = hello | |
.map(String::toUpperCase) | |
.orElseGet(() -> { | |
//.. extra computation to retrieve the value | |
return "world"; | |
}); | |
System.out.println(orElse); | |
// 3. check if hello exists | |
// otherwise world will display. | |
hello.ifPresentOrElse(System.out::println, () -> System.out.println("World")); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment