Contains method for Iterable and Iterator?

Guava has the functions Iterables.contains and Iterators.contains which do what you want. You can look at the source to see how to implement them yourself.


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