How can I turn a List of Lists into a List in Java 8?
The flatMap
method on Stream
can certainly flatten those lists for you, but it must create Stream
objects for element, then a Stream
for the result.
You don't need all those Stream
objects. Here is the simple, concise code to perform the task.
// listOfLists is a List<List<Object>>.
List<Object> result = new ArrayList<>();
listOfLists.forEach(result::addAll);
Because a List
is Iterable
, this code calls the forEach
method (Java 8 feature), which is inherited from Iterable
.
Performs the given action for each element of the
Iterable
until all elements have been processed or the action throws an exception. Actions are performed in the order of iteration, if that order is specified.
And a List
's Iterator
returns items in sequential order.
For the Consumer
, this code passes in a method reference (Java 8 feature) to the pre-Java 8 method List.addAll
to add the inner list elements sequentially.
Appends all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection's iterator (optional operation).
You can use flatMap
to flatten the internal lists (after converting them to Streams) into a single Stream, and then collect the result into a list:
List<List<Object>> list = ...
List<Object> flat =
list.stream()
.flatMap(List::stream)
.collect(Collectors.toList());
flatmap
is better but there are other ways to achieve the same
List<List<Object>> listOfList = ... // fill
List<Object> collect =
listOfList.stream()
.collect(ArrayList::new, List::addAll, List::addAll);