This post will discuss how to convert an array to Iterable in Java.

1. Using 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

2. Using Java 7

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

Download  Run Code

Output:

1
2
3
4
5

3. Using Guava Library

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 the asList() method provided by each primitive class.

Download Code

Output:

1
2
3
4
5

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

Download Code

Output:

1
2
3
4
5

4. Using Arrays.stream() method

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. Using of() method

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 the 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 iterable over the array.

Download  Run Code

Output:

1
2
3
4
5

That’s all about converting an array to Iterable in Java.