Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get ordered stream from a list in reverse order in Java 8

Is there a sane way to get an ordered stream from a list (array list specifically, but it shouldn't matter) that streams elements in reverse of how they are in the original list?

I'm looking for a solution that doesn't involve buffering data in anything (collector, another list, array, etc, because they copy the container which is wasteful), or uses Collections.reverse (because it modifies the list).

So far, the cleanest ways that I see here is to implement my own version of Spliterator that's ORDERED and advances through the list in reverse, or implement an Iterator that iterates in reverse, and use Spliterators.spliteratorUnknownSize(iterator,ORDERED) on it.

Note this question is different from Java 8 stream reverse order : that other question asks on how to reverse a stream (which is impossible in general case), and answers offer to reverse the source somehow (which I don't want to do), and then stream that reversed source. The cost of reversing the source is O(N), and I want to avoid it at all if possible.

like image 629
Pawel Veselov Avatar asked Apr 02 '15 01:04

Pawel Veselov


People also ask

How do you reverse a List in java stream?

The first approach would be to collect() the stream into a list - and then use the Collections. reverse() method on the list, which reverses it in-place. Note: If you also want to sort the collection while reversing it, you can use the sorted(Comparator. reverseOrder()) method in the chain.

How do I sort a List in streams?

Sorting a List of Integers with Stream. Found within the Stream interface, the sorted() method has two overloaded variations that we'll be looking into. This methods returns a stream consisting of the elements of the stream, sorted according to natural order - the ordering provided by the JVM.


1 Answers

If your List is a random access list, you may simply use

int num=list.size()-1;
IntStream.rangeClosed(0, num).mapToObj(i->list.get(num-i))

to create a Stream which has the characteristics ORDERED | SIZED | SUBSIZED and offers full splitting support.

For a non-random access list like LinkedList it would be a performance disaster, however, who uses LinkedList anyway?

You may also check via list instanceofRandomAccess first…

like image 128
Holger Avatar answered Oct 07 '22 22:10

Holger