Reputation: 71
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
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