Convert List Of Lists Into List | Java




In Java, you can flatten a list of lists into a single list using various approaches. One common way is to use streams and `flatMap()`.

Here's an example using Java 8 streams:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class FlattenList {
    public static void main(String[] args) {
        List<List<Integer>> listOfLists = Arrays.asList(
                Arrays.asList(1, 2, 3),
                Arrays.asList(4, 5),
                Arrays.asList(6, 7, 8)
        );

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

        System.out.println("Original List of Lists: " + listOfLists);
        System.out.println("Flattened List: " + flattenedList);
    }
}

In this example, `listOfLists.stream().flatMap(List::stream)` flattens the nested lists into a single stream of elements, and then `collect(Collectors.toList())` is used to collect those elements into a new list.



If you are using a version of Java older than Java 8 and don't have access to streams, you can achieve the same result using nested loops:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class FlattenList {
    public static void main(String[] args) {
        List<List<Integer>> listOfLists = Arrays.asList(
                Arrays.asList(1, 2, 3),
                Arrays.asList(4, 5),
                Arrays.asList(6, 7, 8)
        );

        List<Integer> flattenedList = new ArrayList<>();

        for (List<Integer> innerList : listOfLists) {
            flattenedList.addAll(innerList);
        }

        System.out.println("Original List of Lists: " + listOfLists);
        System.out.println("Flattened List: " + flattenedList);
    }
}

This code iterates through the outer list and, for each inner list, adds its elements to the flattened list.


Post a Comment

Previous Post Next Post