Search code examples
javacollectionsiteratoriterable

Contains method for Iterable and Iterator?


Is there a simple method to check if an element is contained in an iterable or iterator, analogous to the Collection.contains(Object o) method?

I.e. instead of having to write:

Iterable<String> data = getData();
for (final String name : data) {
    if (name.equals(myName)) {
        return true;
    }
}

I would like to write:

Iterable<String> data = getData(); 
if (Collections.contains(data, myName)) {
    return true;
}

I'm really surprised there is no such thing.


Solution

  • In Java 8, you can turn the Iterable into a Stream and use anyMatch on it:

    String myName = ... ;
    Iterable<String> data = getData();
    
    return StreamSupport.stream(data.spliterator(), false)
                        .anyMatch(name -> myName.equals(name));
    

    or using a method reference,

    return StreamSupport.stream(data.spliterator(), false)
                        .anyMatch(myName::equals);