Chaining of Java Optional map and orElse (if-else-style)

孤人 提交于 2019-12-20 03:06:04

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!