我想使用流畅的api Optional并应用两个Consumers.
我在梦想这样的事情:
Optional.ofNullable(key)
.map(Person::get)
.ifPresent(this::printName)
.ifPresent(this::printAddress); // not compiling, because ifPresent is void
Run Code Online (Sandbox Code Playgroud)
我该如何申请几个Consumers到的Optional?
小智 13
以下是如何实现缺少的peek方法Optional:
<T> UnaryOperator<T> peek(Consumer<T> c) {
return x -> {
c.accept(x);
return x;
};
}
Run Code Online (Sandbox Code Playgroud)
用法:
Optional.ofNullable(key)
.map(Person::get)
.map(peek(this::printName))
.map(peek(this::printAddress));
Run Code Online (Sandbox Code Playgroud)
sla*_*dan 10
您可以使用以下语法:
ofNullable(key)
.map(Person::get)
.map(x -> {printName(x);return x;})
.map(x -> {printAddress(x);return x;});
Run Code Online (Sandbox Code Playgroud)
tob*_*s_k 10
虽然这看起来可能不太优雅,但我只想将两种方法合并为一种,lambda并将其传递给ifPresent:
ofNullable(key)
.map(Person::get)
.ifPresent(x -> {printName(x); printAddress(x);});
Run Code Online (Sandbox Code Playgroud)
或者,您也可以使用andThen链接多个使用者,尽管这需要您将方法引用转换为Consumer,这也不是很优雅.
ofNullable(key)
.map(Person::get)
.ifPresent(((Consumer) this::printName).andThen(this::printAddress));
Run Code Online (Sandbox Code Playgroud)
Java 8 替代 ( map+ orElseGet):
Optional.ofNullable(key)
.map(Person::get) // Optional<Person>
.map(Stream::of) // Optional<Stream<Person>>
.orElseGet(Stream::empty) // Stream<Person>
.peek(this::printName)
.peek(this::printAddress)
.findAny();
Run Code Online (Sandbox Code Playgroud)
随着新流的可选API作为JDK9的方法,你可以调用stream方法从转变Optional<T>到Stream<T>,然后让一个peek,然后,如果你想回去的Optional<T>只是调用findFirst()或findAny()。
您的例子:
Optional.ofNullable(key)
.map(Person::get) // Optional<Person>
.stream() // Stream<Person>
.peek(this::printName)
.peek(this::printAddress)
...
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3721 次 |
| 最近记录: |