java ifPresent Stream 的 Else 方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32704551/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Else method for ifPresent Stream
提问by Johnny Willer
I want to know how to do some behavior if some value is not present after filter a stream.
如果过滤流后不存在某些值,我想知道如何做一些行为。
Let's suppose that code:
让我们假设代码:
foo.stream().filter(p -> p.someField == someValue).findFirst().ifPresent(p -> {p.someField = anotherValue; someBoolean = true;});
How I put some kind of Elseafter ifPresentin case of value is not present?
如果值不存在,我如何放置某种Elseafter ifPresent?
There are some orElsemethods on Stream that I can call after findFirst, but I can't see a way to do that with those orElse
orElseStream 上有一些方法可以在 之后调用findFirst,但我看不到用这些方法来做到这一点的方法orElse
回答by Manos Nikolaidis
findFirstreturns an Optionaldescribing the first element of this stream, or an empty Optional if the stream is empty.
findFirst返回一个Optional描述此流的第一个元素的值,如果流为空,则返回一个空的 Optional。
If you want to apply a function when Optionalis not empty you should use map. orElseGetcan call another lambda if Optionalis empty E.g.
如果要在Optional不为空时应用函数,则应使用map. orElseGet如果Optional为空,则可以调用另一个 lambda例如
foo.stream()
.filter(p -> p.someField == someValue)
.findFirst().map(p -> {
p.someField = anotherValue;
someBoolean = true;
return p;
}).orElseGet(() -> {
P p = new P();
p.someField = evenAnotherValue;
someBoolean = false;
return p;
});

