0

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?

kosa
  • 65,990
  • 13
  • 130
  • 167
MTT
  • 5,113
  • 7
  • 35
  • 61

5 Answers5

3

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.

William Morrison
  • 10,953
  • 2
  • 31
  • 48
3

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

Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413
2

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.

Björn Höper
  • 41
  • 2
  • 7
0

try with

iter.toString().toLowerCase().equals("my string")
NFE
  • 1,147
  • 1
  • 9
  • 22
  • That's not the question, I think he wants to do this without iterating through the elements... Why is a mystery, but there it is. – Maarten Bodewes Jun 18 '13 at 18:05
  • Ok. I think the problem like he tried to iterate element and compare with `iter` object directly. – NFE Jun 18 '13 at 18:08
  • @VTT so this was about `Iterator` and not `Iterable`? – Maarten Bodewes Jun 18 '13 at 18:13
  • 2
    That is quite an ugly hack which assumes that the specific iterable implements `toString` in a "user-friendly" way. Although it is generally the case you should not rely on that. – assylias Jun 18 '13 at 18:18
  • Yes . He accepted my answer so I think that He concern with `Iterator` – NFE Jun 18 '13 at 18:19
  • Yes, you are right. It was my mistake and lack of knowledge. – MTT Jun 18 '13 at 18:30
  • 1
    This is a poor solution. The toString function on the iterator iterface doesn't necessarily return the string representation of all its contents. – William Morrison Jun 18 '13 at 18:43
0

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?

Community
  • 1
  • 1
lamilambkin
  • 117
  • 1
  • 1
  • 9