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
after ifPresent
in case of value is not present?
There are some orElse
methods on Stream that I can call after findFirst
, but I can't see a way to do that with those orElse
If a value is present, isPresent() will return true and get() will return the value. Additional methods that depend on the presence or absence of a contained value are provided, such as orElse() (return a default value if value not present) and ifPresent() (execute a block of code if the value is present).
The ifPresent method of the Optional class is an instance method that performs an action if the class instance contains a value. This method takes in the Consumer interface's implementation whose accept method will be called with the value of the optional instance as the parameter to the accept method.
isPresent() method returns true if the Optional contains a non-null value, otherwise it returns false. ifPresent() method allows you to pass a Consumer function that is executed if a value is present inside the Optional object. It does nothing if the Optional is empty.
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;
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With