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

375 views Asked by At

I have an Eclipse Collections IntList. How can I

  1. Create a Java IntStream from this list
  2. Create a Java Stream<Integer> from this list

without copying the elements?

2

There are 2 answers

0
Donald Raab On BEST ANSWER

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();
0
Sean Van Gorder On

Edit: Holger's comment 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().