Flatten a List of Lists into a Single List

Situation:
You have a list of lists, and you need to merge them into a single list.

Solution:

List<List<String>> listOfLists = Arrays.asList(Arrays.asList("a", "b"), Arrays.asList("c", "d"));

List<String> flattenedList = listOfLists.stream()
    .flatMap(List::stream)
    .collect(Collectors.toList());

System.out.println(flattenedList);

Explanation:
The flatMap method is used to convert the list of lists into a single stream, which is then collected into a list.

Result:

[a, b, c, d]


Discover more from Byte Code

Subscribe to get the latest posts sent to your email.

Leave a Reply

I’m A Java Enthusiast

Welcome to Byte-Code, your go-to corner of the internet for all things Java. Here, I invite you to join me on a journey through the world of programming, where we’ll explore the intricacies of Java, dive into coding challenges, and build solutions with a touch of creativity. Let’s code something amazing together!

Let’s connect