Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Else method for ifPresent Stream [duplicate]

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

like image 496
Johnny Willer Avatar asked Sep 21 '15 21:09

Johnny Willer


People also ask

How do I return an ifPresent value in Java 8?

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).

How do I use ifPresent optional?

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.

How do I return optional ifPresent?

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.


1 Answers

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;
   });
like image 120
Manos Nikolaidis Avatar answered Oct 24 '22 00:10

Manos Nikolaidis