Question

I have an Iterable and I need to check about a specific string inside the iterable. I tried iter.contains("my string"), but it does not work. Any idea?

Était-ce utile?

La solution 4

try with

iter.toString().toLowerCase().equals("my string")

Autres conseils

Iterable is an interface, it doesn't contain a method like contains because that would assume the underlying data structure could be read sequentially without corruption.

Neither are assumptions the Iterable interface makes.

Your only real option with a bare Iterable is to do a bare for loop:

 for (String string : iterable) {
   if (string.equals(foo)) {
     return true;
   }
 }
 return false;

...or you could call another method which does essentially the same thing, e.g. Guava's Iterables.contains(Iterable, Object).

The Interface Iterable only returns an Iterator. So it is not possible to directly obtain if a certain value is inside. Instead you have to iterate using a for-each structure e.g.

boolean found = false;
for (String s: iter) {
    if (s.equals("my string")) {
        found = true;
        break;
    }
 }

Depending on the Size this may not be very efficient. But if its your only choice...it will work at least.

try to create a iterator object and there is a contains method for iterators in most programming languages

This is a very similar question that has a been answered here Why does Iterator have a contains method but Iterable does not, in Scala 2.8?

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top