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 }
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")
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With