2015-11-11 20:20:04 -08:00
|
|
|
// streams/Optionals.java
|
2016-12-30 17:23:13 -08:00
|
|
|
// (c)2017 MindView LLC: see Copyright.txt
|
2015-11-15 15:51:35 -08:00
|
|
|
// We make no guarantees that this code is fit for any purpose.
|
2016-09-23 13:23:35 -06:00
|
|
|
// Visit http://OnJava8.com for more book information.
|
2015-11-11 20:20:04 -08:00
|
|
|
import java.util.*;
|
|
|
|
import java.util.stream.*;
|
|
|
|
import java.util.function.*;
|
|
|
|
|
2015-11-14 16:18:05 -08:00
|
|
|
public class Optionals {
|
2015-11-11 20:20:04 -08:00
|
|
|
static void basics(Optional<String> optString) {
|
|
|
|
if(optString.isPresent())
|
|
|
|
System.out.println(optString.get());
|
|
|
|
else
|
|
|
|
System.out.println("Nothing inside!");
|
|
|
|
}
|
2016-11-21 12:37:57 -08:00
|
|
|
static void ifPresent(Optional<String> optString) {
|
2015-11-14 16:18:05 -08:00
|
|
|
optString.ifPresent(System.out::println);
|
2015-11-11 20:20:04 -08:00
|
|
|
}
|
2016-11-21 12:37:57 -08:00
|
|
|
static void orElse(Optional<String> optString) {
|
2015-11-11 20:20:04 -08:00
|
|
|
System.out.println(optString.orElse("Nada"));
|
|
|
|
}
|
2016-11-21 12:37:57 -08:00
|
|
|
static void orElseGet(Optional<String> optString) {
|
2015-11-11 20:20:04 -08:00
|
|
|
System.out.println(
|
|
|
|
optString.orElseGet(() -> "Generated"));
|
|
|
|
}
|
2016-11-21 12:37:57 -08:00
|
|
|
static void orElseThrow(Optional<String> optString) {
|
2015-11-11 20:20:04 -08:00
|
|
|
try {
|
|
|
|
System.out.println(optString.orElseThrow(
|
2015-12-02 09:20:27 -08:00
|
|
|
() -> new Exception("Supplied")));
|
2015-11-11 20:20:04 -08:00
|
|
|
} catch(Exception e) {
|
|
|
|
System.out.println("Caught " + e);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
static void
|
|
|
|
test(String testName, Consumer<Optional<String>> cos) {
|
|
|
|
System.out.println(" === " + testName + " === ");
|
|
|
|
cos.accept(Stream.of("Epithets").findFirst());
|
|
|
|
cos.accept(Stream.<String>empty().findFirst());
|
|
|
|
}
|
|
|
|
public static void main(String[] args) {
|
|
|
|
test("basics", Optionals::basics);
|
2016-11-21 12:37:57 -08:00
|
|
|
test("ifPresent", Optionals::ifPresent);
|
|
|
|
test("orElse", Optionals::orElse);
|
|
|
|
test("orElseGet", Optionals::orElseGet);
|
|
|
|
test("orElseThrow", Optionals::orElseThrow);
|
2015-11-11 20:20:04 -08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
/* Output:
|
|
|
|
=== basics ===
|
|
|
|
Epithets
|
|
|
|
Nothing inside!
|
|
|
|
=== ifPresent ===
|
|
|
|
Epithets
|
|
|
|
=== orElse ===
|
|
|
|
Epithets
|
|
|
|
Nada
|
|
|
|
=== orElseGet ===
|
|
|
|
Epithets
|
|
|
|
Generated
|
|
|
|
=== orElseThrow ===
|
|
|
|
Epithets
|
|
|
|
Caught java.lang.Exception: Supplied
|
|
|
|
*/
|