Contains method for Iterable and Iterator?

Roland picture Roland · Oct 27, 2014 · Viewed 12.7k times · Source

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.

Answer

Stuart Marks picture Stuart Marks · Oct 28, 2014

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