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:
List<List<T>> lists = ...; List<T> flattenedList = lists.stream() .flatMap(List::stream) .collect(Collectors.toList());
Here's what's happening in this code:
lists.stream()call creates a stream of
flatMap(List::stream)call flattens the stream of lists into a stream of elements. This is done by using the
streammethod of the
Listinterface as the mapping function.
collect(Collectors.toList())call collects the elements of the stream into a
Note that this code assumes that the
List<List<T>> and the
List<T> 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.