Java 8 Streams - Collect and Reverse Stream into List

Java 8 Streams - Collect and Reverse Stream into List

Introduction

A stream represents a sequence of elements and supports different kinds of operations that lead to the desired result. The source of a stream is usually a Collection or an Array, from which data is streamed from.

Streams differ from collections in several ways; most notably in that the streams are not a data structure that stores elements. They're functional in nature, and it's worth noting that operations on a stream produce a result and typically return another stream, but do not modify its source.

To "solidify" the changes, you collect the elements of a stream back into a Collection.

In this guide, we'll take a look at how to collect and reverse a list in Java.

Collect and Reverse a List in Java

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. However, this will impose a completely new relative order of elements.

Let's define a stream with some elements, collect it into a list, reverse the list and print it:

Stream<?> s = Stream.of(1, 2, 3, 4, 5);

List<?> list = s.collect(Collectors.toList());
Collections.reverse(list);
System.out.println(list);

This results in:

[5, 4, 3, 2, 1]

This works well, but there's a simpler way to do this - all in one method. The collectingAndThen() method allows us to chuck in an additional finishing transformation Function besides the collect() method. This way, we can collect the stream and perform the Collections.reverse() call in the same collect() call!

Collect and Reverse a List with collectingAndThen()

If you'd like to read more about collectingAndThen() - read our detailed, definitive Guide to Java 8 Collectors: collectingAndThen()!

Let's take a look at how we can use collectingAndThen() to bundle the transformations into a single call:

Stream<?> s = Stream.of(1, 2, 3, 4, 5);

List<?> list = s.collect(
        Collectors.collectingAndThen(
                Collectors.toList(),
                l -> {Collections.reverse(l); return l; }
        )
);

System.out.println(list);

Here, we've supplied an adapter Collector to the collect() method. The adapted collector runs Collectors.toList(), and a Lambda function to reverse and return the reversed list. Finally - the returned value is assigned to the list reference variable!

If you'd like to read more about Functional Interfaces and Lambda Expressions in Java - read our Guide to Functional Interfaces and Lambda Expressions in Java!

This results in:

[5, 4, 3, 2, 1]

Conclusion

In this short guide, we've taken a look at how you can collect and reverse a stream/list in Java 8, using collect() and Collections.reverse() - individually, and together through the collectingAndThen() method.

Last Updated: December 13th, 2021
Was this article helpful?

Improve your dev skills!

Get tutorials, guides, and dev jobs in your inbox.

No spam ever. Unsubscribe at any time. Read our Privacy Policy.

Hiram KamauAuthor

In addition to catching code errors and going through debugging hell, I also obsess over whether writing in an active voice is truly better than doing it in passive.

Make Clarity from Data - Quickly Learn Data Visualization with Python

Learn the landscape of Data Visualization tools in Python - work with Seaborn, Plotly, and Bokeh, and excel in Matplotlib!

From simple plot types to ridge plots, surface plots and spectrograms - understand your data and learn to draw conclusions from it.

Want a remote job?

    © 2013-2022 Stack Abuse. All rights reserved.

    DisclosurePrivacyTerms