Java 8 - Collect and Shuffle List or Stream

In this short Byte - we'll take a look at how you can collect and shuffle a list in Java, using the Functional API, and paired with the collectingAndThen() collector.

Advice: If you'd like to read more about collectingAndThen() - read our in-depth "Guide to Java 8 Collectors: collectingAndThen()"!

Collect and Shuffle a List in Java

When collecting a stream back into a list (streamed from a Java Collection) - you may decide to shuffle it. Using Java 8's Functional API - working with streams is efficient and simple.

An intuitive method to make use of here is collectingAndThen() which allows you to collect() a Stream and then run an anonymous function on the result:

public class Shuffle {
    private final Stream<?> stream;
    
    public List<?> getList() {
        return stream.collect(
            collectingAndThen(
                toList(),
                l -> {
                    Collections.shuffle(l);
                    return l;
                }
            )
        );
    }    
}

Here, we've collected the stream into a List, which is a terminal operation (ending the stream). Then, that list is streamed again, utilizing the central Collections.shuffle() method, which accepts any valid Collection and shuffles it in-place.

You can test the method and assert the correct output with:

@Test
public void shouldShuffleList() {
    Shuffle shuffle = new Shuffle(Stream.of(1,2,3));
    List<?> list = shuffle.getList();
    
    assertNotEquals("[1, 2, 3]", list.toString());
}

Conclusion

In this short Byte - we took a look at how you can collect and shuffle a list or stream in Java 8+.

Last Updated: January 18th, 2023
Was this helpful?
David LandupAuthor

Entrepreneur, Software and Machine Learning Engineer, with a deep fascination towards the application of Computation and Deep Learning in Life Sciences (Bioinformatics, Drug Discovery, Genomics), Neuroscience (Computational Neuroscience), robotics and BCIs.

Great passion for accessible education and promotion of reason, science, humanism, and progress.

© 2013-2024 Stack Abuse. All rights reserved.

AboutDisclosurePrivacyTerms