Search code examples
javalambdajava-8

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 }

Solution

  • 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")
        );