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;
   });
Share:
28,245
Johnny Willer
Author by

Johnny Willer

Dev that loves learning new things. Always enjoy each moment of your life.

Updated on July 22, 2020

Comments

  • Johnny Willer
    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 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

  • Johnny Willer
    Johnny Willer over 8 years
    Ok, but if I want to execute an instruction in orElse? example, I want to execute p.someField = evenAnotherValue; someBoolean = false; How could I do that with your approach?
  • Manos Nikolaidis
    Manos Nikolaidis over 8 years
    The 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
    Johnny Willer over 8 years
    Nice, it worked as expected.