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

后端 未结 1 1861
自闭症患者
自闭症患者 2021-01-21 16:57

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\"?

相关标签:
1条回答
  • 2021-01-21 17:45

    You don't need the orElse clause:

    Optional<Float> amount = ...;
    Optional<MonetaryAmount> myAmount =
        amount.map(theAmount -> FastMoney.of(theAmount, "EUR"));
    
    0 讨论(0)
提交回复
热议问题