How to check if element exists using a lambda expression?

JavaJava 8Lambda

Java Problem Overview


Specifically, I have TabPane, and I would like to know if there is element with specific ID in it.

So, I would like to do this with lambda expression in Java:

boolean idExists = false;
String idToCheck = "someId";

for (Tab t : tabPane.getTabs()){
    if(t.getId().equals(idToCheck)) {
        idExists = true;
    }
}

Java Solutions


Solution 1 - Java

Try to use anyMatch of Lambda Expression. It is much better approach.

 boolean idExists = tabPane.getTabs().stream()
            .anyMatch(t -> t.getId().equals(idToCheck));

Solution 2 - Java

While the accepted answer is correct, I'll add a more elegant version (in my opinion):

boolean idExists = tabPane.getTabs().stream()
    .map(Tab::getId)
    .anyMatch(idToCheck::equals);

Don't neglect using Stream#map() which allows to flatten the data structure before applying the Predicate.

Solution 3 - Java

The above answers require you to malloc a new stream object.

public <T>
boolean containsByLambda(Collection<? extends T> c, Predicate<? super T> p) {

    for (final T z : c) {
        if (p.test(z)) {
            return true;
        }
    }
    return false;
}

public boolean containsTabById(TabPane tabPane, String id) {
    return containsByLambda(tabPane.getTabs(), z -> z.getId().equals(id));
}
...
if (containsTabById(tabPane, idToCheck))) {
   ...
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMiljacView Question on Stackoverflow
Solution 1 - JavaMasudulView Answer on Stackoverflow
Solution 2 - JavajFreneticView Answer on Stackoverflow
Solution 3 - JavakevinarpeView Answer on Stackoverflow