Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the reasons for not having an index in Java 8 streams?

I was wondering about the Java 8 streams (Stream<E>), they have the following methods:

  • forEach(Consumer<? super E> action)
  • forEachOrdered(Consumer<? super E> action)

What were the arguments against not supplying the following signature?

  • forEachOrdered(BiConsumer<Integer, ? super E> action)
    • Which would then return the index of the item in the stream and the item itself.

With this overload it would be possible to actually use the index in case the stream was ordered.

I am really curious to see what the arguments are against it.

Edit, the same actually holds for Iterator<E> with forEachRemaining, and possibly more classes.
If none of the classes provide such option, then I suspect it has been considered for Java 8 and denied.

like image 504
skiwi Avatar asked Apr 01 '14 14:04

skiwi


People also ask

Can we get index in stream?

Unlike the Collection elements, Stream elements cannot be accessed through indices, but there are still workarounds to get indices of the elements.

How do you index a stream map?

Create an AtomicInteger for index. Get the Stream from the array using Arrays. stream() method. Map each elements of the stream with an index associated with it using map() method where the index is fetched from the AtomicInteger by auto-incrementing index everytime with the help of getAndIncrement() method.

Why streams are introduced in Java 8?

Introduced in Java 8, the Stream API is used to process collections of objects. A stream is a sequence of objects that supports various methods which can be pipelined to produce the desired result. A stream is not a data structure instead it takes input from the Collections, Arrays or I/O channels.

What is the benefit of Stream in Java 8?

There are a lot of benefits to using streams in Java, such as the ability to write functions at a more abstract level which can reduce code bugs, compact functions into fewer and more readable lines of code, and the ease they offer for parallelization.


2 Answers

indexing every element requires a sequential assignment of the indexes. this would defeat the point of parallel operations, since each operation would have to synchronize to get its index.

like image 100
aepurniet Avatar answered Oct 26 '22 14:10

aepurniet


Streams and Iterators do not have to be finite. Both Stream::generate and Stream::iterate return infinite Streams. How would you handle indexing with an infinite stream? Let the index overflow to negative numbers? Use a BigInteger (and potentially run out of memory)?

There isn't a good solution to handling indexing for infinite streams, so the designers (correctly, in my opinion) left it out of the API.

like image 33
Jeffrey Avatar answered Oct 26 '22 14:10

Jeffrey