Reverse a Sequential Stream in Java

In this post, we will discuss how to reverse a sequential Stream in Java. Since streams don’t store any elements, an intermediate collection is used to create a new stream which iterates elements of the specified stream in reverse order.


1. Using LinkedList

Simplest solution is to use Linked List data structure. We know that the LinkedList class in Java is implemented as a stack and supports insertion in the beginning. So the idea is to insert elements of the specified stream into a LinkedList and return stream to that list.


Download   Run Code


2. Using Collectors

Another simple solution involves using Collectors. We can use collectingAndThen() method to adapt the toList() collector to produce a list in reverse order as shown below:


Download   Run Code

Since LinkedList class in Java supports insertion at the front, it provides descending iterators. We can use this to iterate the Stream in reverse order as shown below:


Download   Run Code


ArrayDeque can also be used in place of LinkedList:


Download   Run Code


3. Collector.of() –

Collector interface provides static factory methods of(Supplier, BiConsumer, BinaryOperator, Characteristics...) can be used to construct collectors. The idea is to create a collector that accumulates elements of the specified Stream into an ArrayList in reverse order.


Download   Run Code


Above solution requires the count of elements in the stream in advance. We can avoid that by using ArrayDeque in place of an ArrayList.


Download   Run Code


1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5.00 out of 5)


Thanks for reading.

Please use our online compiler to post code in comments. To contribute, get in touch with us.
Like us? Please spread the word and help us grow. Happy coding 🙂

Leave a Reply

Notify of