Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 }
like image 226
Bilgin Silahtaroğlu Avatar asked Oct 29 '25 19:10

Bilgin Silahtaroğlu


1 Answers

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")
    );
like image 124
Pshemo Avatar answered Oct 31 '25 09:10

Pshemo