Convert an Array to Iterable in Java

In this post, we will see how to convert an Array to Iterable in Java.

 

1. Java 7 and before

With java 7 and before, we can do something like:

 

Download   Run Code

Output:

1
2
3
4
5

 

2. Java 8 and above

In java 8 and above, we can use lambda to convert the iterator to iterable as shown below:

 

Download   Run Code

Output:

1
2
3
4
5

 

3. Using Guava

Guava’s com.google.common.primitives package provides utility classes for all primitives types such as Ints, Doubles, Longs, Chars, etc. To get an iterable, we can wrap the specified primitive array as a List of the corresponding wrapper type using asList() method provided by each primitive class.

 

Download   Run Code

Output:

1
2
3
4
5

 
For Wrapper classes or arrays with non-primitive types, we can use Iterators.forArray() method to get an Iterator and we can easily get an Iterable from the iterator using lambda as already seen before.

 

Download   Run Code

Output:

1
2
3
4
5

 

4. Java 8 – Arrays.stream()

The idea is to get an Iterator by calling the iterator() method on IntStream, DoubleStream or LongStream. Then we get an Iterable from the iterator using lambda.

 

Download   Run Code

Output:

1
2
3
4
5

 

5. Java 8 – IntStream.of() DoubleStream.of() or LongStream.of()

We can also use IntStream.of(), DoubleStream.of() or LongStream.of() in place of overloaded Arrays.stream() for int, double and long values respectively.

 

Download   Run Code

Output:

1
2
3
4
5

 

For Non-Primitive Arrays

A List is an Iterable in Java since List interface extends the java.util.Collection interface, which happens to extend the java.lang.Iterable interface. So for non-primitive arrays, we can simply use Arrays.asList() to get an iterable over the array.

 

Download   Run Code

Output:

1
2
3
4
5

 
Thanks for reading.




Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 





Leave a Reply

Notify of
avatar
wpDiscuz