-
Enhancement
-
Resolution: Fixed
-
P4
-
None
-
b89
Issue | Fix Version | Assignee | Priority | Status | Resolution | Resolved In Build |
---|---|---|---|---|---|---|
JDK-8142752 | emb-9 | Paul Sandoz | P4 | Resolved | Fixed | team |
Currently there is no simple way to execute a supplier if current Optional is empty,
that can be seen as the the dual of flatMap() that executes a function if the current Optional is not empty.
A possible workaround is to use
map(Optional::of).orElseGet(supplier)
which while working create an unnecessary Optional and is less readable.
The proposed implementation (by Paul Sandoz):
public Optional<T> or(Supplier<Optional<T>> mapper) {
Objects.requireNonNull(mapper);
if (isPresent()) {
return this;
} else {
return Objects.requireNonNull(mapper.get());
}
}
For more information, here is the relevant discussion on core-dev:
http://mail.openjdk.java.net/pipermail/core-libs-dev/2015-April/032904.html
that can be seen as the the dual of flatMap() that executes a function if the current Optional is not empty.
A possible workaround is to use
map(Optional::of).orElseGet(supplier)
which while working create an unnecessary Optional and is less readable.
The proposed implementation (by Paul Sandoz):
public Optional<T> or(Supplier<Optional<T>> mapper) {
Objects.requireNonNull(mapper);
if (isPresent()) {
return this;
} else {
return Objects.requireNonNull(mapper.get());
}
}
For more information, here is the relevant discussion on core-dev:
http://mail.openjdk.java.net/pipermail/core-libs-dev/2015-April/032904.html
- backported by
-
JDK-8142752 Add Optional.or()
-
- Resolved
-
- duplicates
-
JDK-8086066 Proposal for Optional.or()
-
- Closed
-