How to convert Java Array to Iterable?

Java 8Object Oriented ProgrammingProgramming

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());
}
raja
Published on 09-Jan-2018 07:25:22
Advertisements