Bilgin Silahtaroğlu
Bilgin Silahtaroğlu

Reputation: 71

Lambda - if anyMatch do something orElse do something

Can I do this all logic with using one lambda expression?

boolean isTrue = myList.stream().anyMatch( m -> m.getName().equals("a") );         
         
if (isTrue) { do something } 
else { do other thing }

Upvotes: 4

Views: 13104

Answers (1)

Pshemo
Pshemo

Reputation: 124235

Since Java 9 Optional class added

public void ifPresentOrElse​(Consumer<? super T> action, Runnable emptyAction)

Also instead of anyMatch(<<yourCondition>>) which returns boolean you can use filter(<<yourCondition>>).findAny() which returns Optional.

So you can combine it and write code like

yourStream
    .filter(m -> m.getName().equals("a")) //your condition
    .findAny() //returns Optional
    .ifPresentOrElse(
        // action when value exists 
        value -> System.out.println("There was a value "+value),

        // action when there was no value
        () -> System.out.println("No value found")
    );

Upvotes: 11

Related Questions