Last active
July 27, 2019 08:07
-
-
Save will-molloy/55d4ba61fcaf4aada621e0a006759d69 to your computer and use it in GitHub Desktop.
Chaining Optional (Java 9 Optional#or)
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
import java.util.Optional; | |
class ChainingOptional { | |
static Optional<Integer> get1() { | |
return Optional.empty(); | |
} | |
static Optional<Integer> get2() { | |
return Optional.empty(); | |
} | |
static Optional<Integer> get3() { | |
return Optional.of(3); | |
} | |
public static void main(String[] args) { | |
var integer = get1().or(() -> get2()).or(() -> get3()).orElseThrow(); | |
System.out.println(integer); // 3 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment