Fundamentals

Default Methods

Collections

Idioms and Techniques

Design Rationale

Advanced Questions

How can I turn an array into an Iterator?

If you have an array of reference type, the easiest way is to turn it into a List. Nothing new here:

MyObject[] array = ... ;
Iterator<MyObject> iterator = Arrays.asList(array).iterator();

Difficulties arise if you have an array of primitives. If you have an int array, passing it to Arrays.asList() doesn’t result in a List<Integer>. Instead, you get a List<int[]>, which is probably not what you want!

The problem with Iterator in this case is that it can only iterate over elements of reference type, not primitives. You can create an Iterator of boxed primitives from a primitive array (at from least our usual trio of int, long, and double) by first wrapping the array in a Stream and then getting an Iterator from that:

int[] array = ... ;
Iterator<Integer> iterator = Arrays.stream(array).iterator();

You can use this Iterator in the usual way. Note however that every call to next() will end up boxing the primitive value, which incurs some overhead. If you want to use Iterator-style constructs but avoid boxing overhead, you can use the new primitive Iterators introduced in Java 8. It turns out that the Iterator returned by a primitive stream such as IntStream is both an Iterator<Integer> and the new PrimitiveIterator.OfInt. This new iterator has a method nextInt() that returns the int value from the Iterator without boxing it. It can be used as follows:

PrimitiveIterator.OfInt intIterator = Arrays.stream(array).iterator();
while (intIterator.hasNext()) {
    methodTakingInt(intIterator.nextInt());
}

The same applies to long and double iterators, which have analogous nextLong() and nextDouble() methods.

Converting primitive arrays to primitive streams probably satisfies most use cases. However, these alternative mechanisms exist that allow you to create long-standing Iterator-style constructs should they be necessary.