java not present_Java 8的可选的function.ifPresent和if-not-present的功能风格?

对我来说@Dane White的答案是OK,首先我不喜欢使用Runnable,但我找不到任何替代品,这里另一个实现我喜欢更多

public class OptionalConsumer {

private Optional optional;

private OptionalConsumer(Optional optional) {

this.optional = optional;

}

public static OptionalConsumer of(Optional optional) {

return new OptionalConsumer<>(optional);

}

public OptionalConsumer ifPresent(Consumer c) {

optional.ifPresent(c);

return this;

}

public OptionalConsumer ifNotPresent(Runnable r) {

if (!optional.isPresent())

r.run();

return this;

}

}

然后 :

Optional o = Optional.of(...);

OptionalConsumer.of(o).ifPresent(s ->System.out.println("isPresent "+s))

.ifNotPresent(() -> System.out.println("! isPresent"));

更新1:

上面的解决方案为传统的开发方式,当你有价值,想要处理它,但如果我想定义的功能和执行,那么,检查下面的增强;

public class OptionalConsumer implements Consumer> {

private final Consumer c;

private final Runnable r;

public OptionalConsumer(Consumer c, Runnable r) {

super();

this.c = c;

this.r = r;

}

public static OptionalConsumer of(Consumer c, Runnable r) {

return new OptionalConsumer(c, r);

}

@Override

public void accept(Optional t) {

if (t.isPresent())

c.accept(t.get());

else

r.run();

}

}

然后可用作:

Consumer> c=OptionalConsumer.of(System.out::println, ()->{System.out.println("Not fit");});

IntStream.range(0, 100).boxed().map(i->Optional.of(i).filter(j->j%2==0)).forEach(c);

在这个新的代码,你有3件事:

>可以在存在对象之前定义功能容易。

>不为每个可选创建对象引用,只有一个,你有那么少的内存,那么少GC。

>它正在实现消费者以更好地使用其他组件。

现在它的名字更具描述性,它实际上是Consumer>

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值