Else Method for ifPresent Stream

I want to know how to do some kind of behavior if some value is missing after filtering the stream.

Assume the code:

foo.stream().filter(p -> p.someField == someValue).findFirst().ifPresent(p -> {p.someField = anotherValue; someBoolean = true;}); 

How do I put some Elseafter ifPresentin case the value is missing?

There are several methods in Stream orElsethat I can call after findFirst, but I see no way to do this with theseorElse

+4
source share
1 answer

findFirstreturns Optionaldescribing the first element of this stream, or empty Optional if the stream is empty.

, Optional , map. orElseGet , Optional . ,

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;
   });
+5

Source: https://habr.com/ru/post/1608378/


All Articles