对我来说@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>