Elvis java,如何在Java 8中实现Elvis运算符?

I have the classic "Elvis operator" case, where I'm calling methods that each may return null and chaining them together:

thing?:nullableMethod1(a)?:nullableMethod2(b)?:nullableMethod3()

In Java 8, the most faithful implementation I've found is something like this:

return Optional.ofNullable(thing)

.flatMap(x -> Optional.ofNullable(x.nullableMethod1(a)))

.flatMap(y -> Optional.ofNullable(y.nullableMethod2(b)))

.flatMap(z -> Optional.ofNullable(z.nullableMethod3()))

I wish that Java's Optional had something akin to the elvis operator:

public Optional elvisOperator(Function super T, ? extends U> mapper) {

return flatMap(t -> Optional.ofNullable(mapper.apply(t));

}

So that I wouldn't have to wrap each return value:

return Optional.ofNullable(thing)

.elvisOperator(x -> x.nullableMethod1(a))

.elvisOperator(y -> y.nullableMethod2(b))

.elvisOperator(Z::nullableMethod3); // also nice

Is there a more efficient and idiomatic way to implement the Elvis operator pattern in Java 8?

解决方案

Maybe I'm overlooking something, but is there a reason that you can't use Optional#map?

The following example prints nothing, as Optional is short-circuiting in the sense that, if the value inside the Optional doesn't exist (it's null or the Optional is empty), it's treated as empty.

Optional.ofNullable("test")

.map(s -> null)

.ifPresent(System.out::println);

For that reason, I'd think you could just do the following:

return Optional.ofNullable(thing)

.map(x -> x.nullableMethod1(a))

.map(y -> y.nullableMethod2(b))

.map(Z::nullableMethod3);

This would map your thing if it exists, or return an empty Optional otherwise.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值