Java 8 - Collect and Turn Stream into Singleton Set

In this short Byte - we'll take a look at how you can collect and turn a list into a singleton set 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()"!

Turn a Stream into a Singleton Set

When collecting a stream back into a list (streamed from a Java Collection) - you may decide to decide to return an immutable singleton Set that contains a single (and strictly single) immutable element.

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 Singleton {
    private final Stream<?> stream;
    
    public Set<?> getSingleton() {
        return stream.collect(
            collectingAndThen(
                toList(),
                l -> {
                    if (l.size() > 1){
                        throw new RuntimeException();
                    } else{
                        return l.isEmpty()
                            ? emptySet()
                            : singleton(l.get(0));
                    }
                }
            )
        );
    }
}
Get free courses, guided projects, and more

No spam ever. Unsubscribe anytime. Read our Privacy Policy.

Here, we've collected the stream into a List, which is a terminal operation (ending the stream). Then, that list is streamed again, checking for the size. If the size is larger than 1 - a singleton Set cannot be created. In this example, we anticipate that the operation pipeline before the collectingAndThen() call, the stream is filtered of all elements but one.

After the size check - we can create a new singleton Set with singleton(l.get(0)) - passing the first (and only) element of the list into the Collections.singleton() method.

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

@Test
public void shouldCreateSingleton() {
    Singleton s1 = new Singleton(Stream.of(1,2));
    assertThrows(
        RuntimeException.class, 
        () -> s1.getSingleton()
    );
    
    Singleton s2 = new Singleton(Stream.empty());
    Set<?> singleton = s2.getSingleton();
    assertEquals("[]", singleton.toString());
    
    Singleton s3 = new Singleton(Stream.of(1));
    singleton = s3.getSingleton();
    assertEquals("[1]", singleton.toString());
}

Conclusion

In this short Byte - we took a look at how you can collect and turn a list into a singleton set 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