Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 789
Jochen Avatar asked Apr 03 '19 15:04

Jochen


2 Answers

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();
like image 88
Donald Raab Avatar answered Sep 16 '22 15:09

Donald Raab


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().

like image 43
Sean Van Gorder Avatar answered Sep 20 '22 15:09

Sean Van Gorder