Else method for ifPresent Stream
28,245
findFirst
returns an Optional
describing the first element of this stream, or an empty Optional if the stream is empty.
If you want to apply a function when Optional
is not empty you should use map
. orElseGet
can call another lambda if Optional
is empty E.g.
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;
});
Author by
Johnny Willer
Dev that loves learning new things. Always enjoy each moment of your life.
Updated on July 22, 2020Comments
-
Johnny Willer over 3 years
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
Else
afterifPresent
in case of value is not present?There are some
orElse
methods on Stream that I can call afterfindFirst
, but I can't see a way to do that with thoseorElse
-
Johnny Willer over 8 yearsOk, but if I want to execute an instruction in
orElse
? example, I want to executep.someField = evenAnotherValue; someBoolean = false;
How could I do that with your approach? -
Manos Nikolaidis over 8 yearsThe idea is that if Optional is empty you cannot do anything with it.
orElse
is meant to create a new object of whatever type p is and you can call map on that. I'll update the answer -
Johnny Willer over 8 yearsNice, it worked as expected.