Skip to Content

Primitive Iterators in Java 8

You all know the difference between Integer and int in Java? Right? These two ways of working with integers, either as an Object or as a primitive, is the source of much pain. Auto-boxing blurred the differences but there are cases where the JVM cannot get the performance of primitive type with the Object type.

In Java 8, Stream<T> was brought to us and lots. But also IntStream, DoubleStream and LongStream. Lots of methods serve as bridges between the two. For example Stream.mapToInt(ToIntFunction<T>) transforms a Stream<T> into an IntStream. Once you step into the world of primitives, you get better performances without the JVM doing clever things.

Java 8 also brought us OfInt as a more performant replacement for Iterator<Integer>. Here’s an example:

OfInt iterator = IntStream.rangeClosed(1, 1000).iterator();
while (iterator.hasNext()) {
    System.out.println(iterator.nextInt()); // not .next() !!
}

Of course previous code should be written this way instead:

IntStream.rangeClosed(1, 1000).forEach(System.out::println);

It was just to show you how to create an instance of OfInt.

comments powered by Disqus