Defaulting Optional orElse with Optional.empty in Java 8
Combine both the list using Stream.of
and check for element or return Optional.empty()
Stream.of(lunches, dinners)
.flatMap(List::stream)
.filter(s -> s.getName()
.equalsIgnoreCase(name))
.findFirst();
As per the suggestion from @Holger you can also use Stream.concat
to concat two streams and then check for element
Stream.concat(lunches.stream(), dinners.stream())
.filter(s -> s.getName()
.equalsIgnoreCase(name))
.findFirst();
You can do like this too:
Optional<Food> firstTry = lunches.stream()
.filter(f -> f.getName().equalsIgnoreCase(name))
.findFirst();
return firstTry.map(Optional::of)
.orElse(dinners.stream()
.filter(f -> f.getName().equalsIgnoreCase(name)).findFirst());
Or in Java9
firstTry.or(() -> dinners.stream().filter(s -> s.equalsIgnoreCase(name)).findFirst());
As @Slaw commented correctly use of orElseGet()
avoid eagerly computing.
Optional<Food> firstTry = lunches.stream().filter(...)...findFirst();
Supplier<Optional<Food>> secondTry = () -> dinners.stream()...findFirst();
and at the end
return firstTry.map(Optional::of).orElseGet(secondTry);