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)
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.
Unlike the Collection elements, Stream elements cannot be accessed through indices, but there are still workarounds to get indices of the elements.
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.
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.
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.
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.
Stream
s and Iterator
s do not have to be finite. Both Stream::generate
and Stream::iterate
return infinite Stream
s. 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With