Java 8 - Collect and Slice List or Stream

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

Slice a List in Java

When collecting a stream back into a list (streamed from a Java Collection) - you may decide to slice it, given some start and end, effectively returning a sublist of the original one. 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 Slice {
    private final Stream<Integer> s;
    private final int from;
    private final int to;
    
    public List<Integer> getList() {
        return s.collect(
            Collectors.collectingAndThen(
                toList(),
                l -> {
                    return l.stream()
                        .skip(from)
                        .limit(to - (from - 1))
                        .collect(toList());
                }
            )
        );
    }
}

Here, we've collected the stream into a List, which is a terminal operation (ending the stream). Then, that list is streamed again, utilizing skip() and limit() to sublist the original list, collecting back into a List.

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

@Test
public void shouldSliceList() {
    Stream<Integer> stream = IntStream
        .rangeClosed(0, 10)
        .boxed();
    Slice slice = new Slice(stream, 3, 7);
    List<Integer> list = slice.getList();
    
    assertEquals(
        "[3, 4, 5, 6, 7]",
        list.toString()
    );
}

Conclusion

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