The first one iterates over an array of suppliers. The first non-empty Optional<> is returned. If we don't find one, we return an empty Optional.
The second one does the same with a Stream of Suppliers which is traversed, each one asked (lazily) for their value, which is then filtered for empty Optionals. The first non-empty one is returned, or if no such exists, an empty one.
To perform Optional Chaining First convertStream to Optional Using either of the two methods
findAny() or findFirst()
min() / max()
Once optional is obtained optional has two more instance method which are also present in Stream class i.e filter and map().
use these on methods and to check output use ifPresent(System.out :: Println)
for cascading chaining You could useifPresentOrElse
find1().ifPresentOrElse( System.out::println, new Runnable() {
public void run() {
find2().ifPresentOrElse( System.out::println, new Runnable() {
public void run() {
find3().ifPresentOrElse( System.out::println, new Runnable() {
public void run() {
System.err.println( "nothing found…" );
}
} );
}
} );
}
} );
to do something with the value of the Optional You had to replace the System.out::println with Your Consumer (different Consumers would also be possible in this solution)
public static <T> T firstMatch(final Predicate<T> matcher, final T orElse, final T... values) {
for (T t : values) {
if (matcher.test(t)) {
return t;
}
}
return orElse;
}