链接Java可选地图和orElse(if-else-style) [英] Chaining of Java Optional map and orElse (if-else-style)

查看:172
本文介绍了链接Java可选地图和orElse(if-else-style)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中是否有优雅的流媒体方式说如果值存在,则将此可选映射到具有计算值的另一个可选,否则返回空可选?



<我想到了类似的东西:

 可选< Float>金额= ...; 
可选< MonetaryAmount> myAmount = amount
.map(theAmount - > FastMoney.of(theAmount,EUR))。orElse(Optional.empty());

但这是不可能的。



我提出的解决方案有点冗长而且不像流媒体一样:

 可选< Float>金额= ...; 
可选< MonetaryAmount> myAmount = amount.isPresent()?
Optional.of(FastMoney.of(amount.get(),EUR)):Optional.empty();


解决方案

您不需要 orElse 子句:

 可选< Float>金额= ...; 
可选< MonetaryAmount> myAmount =
amount.map(theAmount - > FastMoney.of(theAmount,EUR));


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();

解决方案

You don't need the orElse clause:

Optional<Float> amount = ...;
Optional<MonetaryAmount> myAmount =
    amount.map(theAmount -> FastMoney.of(theAmount, "EUR"));

这篇关于链接Java可选地图和orElse(if-else-style)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆