W3docs

How can I turn a List of Lists into a List in Java 8?

You can use the flatMap method from the Stream API to turn a List<List<T>> (a list of lists) into a List<T> in Java 8. Here's an example of how you can do this:

You can use the flatMap method from the Stream API to turn a List<List&lt;T&gt;> (a list of lists) into a List&lt;T&gt; in Java 8. Here's an example of how you can do this:


List<List&lt;T&gt;> lists = ...;
List&lt;T&gt; flattenedList = lists.stream()
                            .flatMap(List::stream)
                            .collect(Collectors.toList());

Here's what's happening in this code:

  1. The lists.stream() call creates a stream of List&lt;T&gt; elements.
  2. The flatMap(List::stream) call flattens the stream of lists into a stream of elements. This is done by using the stream method of the List interface as the mapping function.
  3. The collect(Collectors.toList()) call collects the elements of the stream into a List&lt;T&gt;.

Note that this code assumes that the List<List&lt;T&gt;> and the List&lt;T&gt; are both non-null. If either of them is null, you will need to handle this case appropriately.

I hope this helps! Let me know if you have any questions.