Create an IntStream and a Stream<Integer> from an Eclipse Collections IntList/IntIterable

Edit: Holger found a much clearer solution:

public static IntStream intListToIntStream(IntList intList) {
    return IntStream.range(0, intList.size()).map(intList::get);
}

After looking into the IntIterator code, it turns out the implementation is equivalent to this, so the below solutions are unnecessary. You can even make this more efficient using .parallel().


If you're on Java 9, you can use this method:

public static IntStream intListToIntStream(IntList intList) {
    IntIterator intIter = intList.intIterator();
    return IntStream.generate(() -> 0)
            .takeWhile(i -> intIter.hasNext())
            .map(i -> intIter.next());
}

Otherwise, I don't see a better solution than wrapping the IntIterator as a PrimitiveIterator.OfInt and building a stream out of that:

public static IntStream intListToIntStream(IntList intList) {
    IntIterator intIter = intList.intIterator();
    return StreamSupport.intStream(Spliterators.spliterator(new PrimitiveIterator.OfInt() {
        @Override
        public boolean hasNext() {
            return intIter.hasNext();
        }
        @Override
        public int nextInt() {
            return intIter.next();
        }
    }, intList.size(), Spliterator.ORDERED), false);
}

Either way, you can just get a Stream<Integer> by calling IntStream.boxed().


With Eclipse Collections 10.0 you can now call primitiveStream directly on IntList.

IntStream intStream = IntLists.mutable.with(1, 2, 3, 4, 5).primitiveStream();

Stream<Integer> stream = intStream.boxed();