Get an Iterator over a primitive array in Java

In this post, we will see how to get an iterator over a primitive array in Java. The iterator should be able to iterate over the values in the specified array.

 
Even though arrays in Java implements java.lang.Cloneable and java.io.Serializable interface and we can even use them in for-each loops, they don’t implement the Iterable interface. But we can easily get an iterator over a primitive array in Java using any of the below discussed methods:

 

1. Writing our own Iterator

Naive solution is write our own Iterator. We just need to override two abstract methods of the Iterator interface – hasNext() and next(). This can be done as demonstrated below:

 

Download   Run Code

Output:

1
2
3
4
5

 

2. Java 8 – Arrays.stream()

Java 8 provides PrimitiveIterator.OfInt, PrimitiveIterator.OfDouble, PrimitiveIterator.OfLong which are nothing but Iterator specialized for int, double and long values respectively. These can be obtained by calling iterator() method on IntStream, DoubleStream and LongStream respectively.

 
To get an Iterator instance, we need to Box of the elements of IntStream, DoubleStream and LongStream before calling the iterator() method. This can be handled implicitly by Java or can be done explicitly using boxed() or mapToObj() methods as shown below.

 

Download   Run Code

Output:

1
1
1

 

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

 

4. Using Guava

Guava provides utility classes for all primitives types such as Ints, Longs, Chars, Doubles, etc in com.google.common.primitives package. The idea is to wrap the primitive array as a List of the corresponding wrapper type using asList() method provided by each primitive class and then call iterator() to get an Iterator.

 

Download   Run Code

Output:

1
2
3
4
5

 

5. Apache Commons Collections

Apache Commons Collections ArrayIterator class implements an Iterator over any primitive or non-primitive array. The idea is to construct an ArrayIterator that can iterate over the values in the specified array.

The advantage of using this is that the iterator implements a reset() method, allowing the reset of the iterator back to the start if required.

 

Download

Output:

1
2
3
4
5

 

 
Also See: Iterator over an Object array in Java

 
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