Convert Java Array to Iterable

ntg picture ntg · Apr 26, 2012 · Viewed 165.8k times · Source

I have an Array of primitives, for example for int, int[] foo. It might be a small sized one, or not.

int foo[] = {1,2,3,4,5,6,7,8,9,0};

What is the best way to create an Iterable<Integer> from it?

Iterable<Integer> fooBar = convert(foo);

Notes:

Please do not answer using loops (unless you can give a good explanation on how the compiler do something smart about them?)

Also note that

int a[] = {1,2,3};
List<Integer> l = Arrays.asList(a);

Will not even compile

Type mismatch: cannot convert from List<int[]> to List<Integer>

Also check Why is an array not assignable to Iterable? before answering.

Also, if you use some library (e.g., Guava), please explain why this is the Best. ( Because its from Google is not a complete answer :P )

Last, since there seems to be a homework about that, avoid posting homeworkish code.

Answer

fmucar picture fmucar · Apr 26, 2012
Integer foo[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };

List<Integer> list = Arrays.asList(foo);
// or
Iterable<Integer> iterable = Arrays.asList(foo);

Though you need to use an Integer array (not an int array) for this to work.

For primitives, you can use guava:

Iterable<Integer> fooBar = Ints.asList(foo);
<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>15.0</version>
    <type>jar</type>
</dependency>

For Java8: (from Jin Kwon's answer)

final int[] arr = {1, 2, 3};
final PrimitiveIterator.OfInt i1 = Arrays.stream(arr).iterator();
final PrimitiveIterator.OfInt i2 = IntStream.of(arr).iterator();
final Iterator<Integer> i3 = IntStream.of(arr).boxed().iterator();