This post will discuss 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 interfaces, 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 following-discussed methods:

1. Writing our own iterator

A 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. Using Arrays.stream() method

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 the iterator() method on IntStream, DoubleStream and LongStream, respectively.

 
To get an Iterator instance, we need to Box 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. Using IntStream.of(), DoubleStream.of(), or LongStream.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
1
1

4. Using Guava Library

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 the asList() method provided by each primitive class and then call iterator() to get an iterator.

Download Code

Output:

1
2
3
4
5

5. Using 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 specified array values.

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 Code

Output:

1
2
3
4
5

That’s all about getting an iterator over a primitive array in Java.

 
Also See:

Get an iterator over an object array in Java