50

So in C#, I can treat a string[] as an IEnumerable<string>.

Is there a Java equivalent?

Michael Myers
  • 188,989
  • 46
  • 291
  • 292
Winston Smith
  • 21,585
  • 10
  • 60
  • 75

5 Answers5

52

Iterable<String> is the equivalent of IEnumerable<string>.

It would be an odditity in the type system if arrays implemented Iterable. String[] is an instance of Object[], but Iterable<String> is not an Iterable<Object>. Classes and interfaces cannot multiply implement the same generic interface with different generic arguments.

String[] will work just like an Iterable in the enhanced for loop.

String[] can easily be turned into an Iterable:

Iterable<String> strs = java.util.Arrays.asList(strArray);

Prefer collections over arrays (for non-primitives anyway). Arrays of reference types are a bit odd, and are rarely needed since Java 1.5.

Tom Hawtin - tackline
  • 145,806
  • 30
  • 211
  • 305
  • 2
    For more info on _why_ you cannot cast between Iterable and Iterable, check out [covariance and contravariance](http://en.wikipedia.org/wiki/Covariance_and_contravariance_%28computer_science%29). – Mark McDonald Aug 20 '11 at 09:32
  • Okay, so now let's address the 500-lb gorilla in the room. How do you use `Iterable`? -- what is the equivalent `yield return` statement in Java? – BrainSlugs83 Oct 05 '14 at 03:11
  • @BrainSlugs83 I think that's a different question. – Tom Hawtin - tackline Oct 05 '14 at 08:19
10

Are you looking for Iterable<String>?

Iterable<T> <=> IEnumerable<T>
Iterator<T> <=> IEnumerator<T>
bruno conde
  • 47,767
  • 15
  • 98
  • 117
5

Iterable <T>

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
Learning
  • 8,029
  • 3
  • 35
  • 46
3

I believe the Java equivalent is Iterable<String>. Although String[] doesn't implement it, you can loop over the elements anyway:

String[] strings = new String[]{"this", "that"};
for (String s : strings) {
    // do something
}

If you really need something that implements Iterable<String>, you can do this:

String[] strings = new String[]{"this", "that"};
Iterable<String> stringIterable = Arrays.asList(strings);
Dan Vinton
  • 26,401
  • 9
  • 37
  • 79
0

Iterable<T> is OK, but there is a small problem. It cannot be used easily in stream() i.e lambda expressions.

If you want so, you should get it's spliterator, and use the class StreamSupport().

Deepend
  • 4,057
  • 17
  • 60
  • 101