This post 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

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

Download  Run Code

2. Using Collectors

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

Download  Run Code

 
Since the 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. Using Collector.of() method

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

 
The above solution requires the count of elements in the stream in advance. We can avoid that by using ArrayDeque in place of an ArrayList, as demonstated below:

Download  Run Code

That’s all about reversing a Sequential Stream in Java.