This post will discuss how to reverse elements of a stream in Java. In other words, create a new stream that iterates the elements of the specified stream in reverse order.

1. Using List

Since streams in Java doesn’t store any elements, the idea is to collect the stream elements into a list, inplace reverse the list using Collections.reverse(), and convert the reversed list back to a stream. We can use the Collectors.toList() method to create an intermediate list and Collectors.collectingAndThen() method to adapt the Collectors.toList() collector to produce a list in reverse order. Here’s an example of how we can achieve this:

Download  Run Code

2. Using LinkedList

A LinkedList class in Java is implemented as a stack and supports insertion at the front. We can take advantage of this fact and collects the stream elements into a LinkedList, then returns a descending iterator over the list. The iterator can be used to traverse the elements in reverse order. Here is a sample code that demonstrates this:

Download  Run Code

3. Using ArrayDeque

The Collector interface provides static factory method Collector.of() that can be used to construct collectors. The idea is to create a custom collector that accumulates the stream elements into an ArrayDeque, adding each element to the front of the deque. Then we can convert the ArrayDeque to a Stream by calling its stream() method. Here is an example of how the code might look like:

Download  Run Code

 
Another option is to use ArrayList instead of an ArrayDeque, but since it adds elements at the end, it is slower and not recommended. We can use it like this:

Download  Run Code

That’s all about reversing elements of a Stream in Java.