How to convert Java Array to Iterable?


To make an array iterable either you need to convert it to a stream or as a list using the asList() or stream() methods respectively. Then you can get an iterator for these objects using the iterator() method.

Example

Live Demo

import java.util.Arrays;
import java.util.Iterator;

public class ArrayToIterable {
   public static void main(String args[]){
      Integer[] myArray = {897, 56, 78, 90, 12, 123, 75};
      Iterator<Integer> iterator = Arrays.stream(myArray).iterator();
      while(iterator.hasNext()) {
         System.out.println(iterator.next());
      }
   }
}

Output

897
56
78
90
12
123
75

As mentioned above, you can also convert an array to list and get an iterator from that list using the iterator() method.

Integer[] myArray = {897, 56, 78, 90, 12, 123, 75};
Iterator<Integer> iterator = Arrays.asList(myArray).iterator();

//Iterator<Integer> iterator = Arrays.stream(myArray).iterator();
while(iterator.hasNext()) {
   System.out.println(iterator.next());
}

Updated on: 16-Jun-2020

8K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements