How do I concisely write a || b where a and b are Optional values?
Optional<Integer> aOrB = a.isPresent() ? a : b;
In java-9 you can follow any of these :
✓ Simply chain it using the or
as :-
Optional<Integer> a, b, c, d; // initialized
Optional<Integer> opOr = a.or(() -> b).or(() -> c).or(() -> d);
implementation documented as -
If a value is present, returns an
Optional
describing the value, otherwise returns anOptional
produced by the supplying function.
✓ Alternatively as pointed out by @Holger, use the stream
as:-
Optional<Integer> opOr = Stream.of(a, b, c, d).flatMap(Optional::stream).findFirst();
implementation documented as -
If a value is present, returns a sequential
Stream
containing only that value, otherwise returns an emptyStream
.
In java-8
we don't have any solution to easy chain Optional
objects, but you can try with:
Stream.of(a, b)
.filter(op -> op.isPresent())
.map(op -> op.get())
.findFirst();
In java9
you can do:
Optional<Integer> result = a.or(() -> b);