问题
Is there an elegant and streaming way in Java to say "map this Optional to another Optional with a computed value if the value exists, else return an empty Optional"?
I thought of something like:
Optional<Float> amount = ...;
Optional<MonetaryAmount> myAmount = amount
.map(theAmount -> FastMoney.of(theAmount, "EUR")).orElse(Optional.empty());
But this is not possible.
The solution I came up with is somewhat verbose and not streaming-like:
Optional<Float> amount = ...;
Optional<MonetaryAmount> myAmount = amount.isPresent() ?
Optional.of(FastMoney.of(amount.get(), "EUR")) : Optional.empty();
回答1:
You don't need the orElse clause:
Optional<Float> amount = ...;
Optional<MonetaryAmount> myAmount =
amount.map(theAmount -> FastMoney.of(theAmount, "EUR"));
来源:https://stackoverflow.com/questions/47571787/chaining-of-java-optional-map-and-orelse-if-else-style