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

后端 未结 9 828
春和景丽
春和景丽 2020-11-22 04:49

If I have a List>, how can I turn that into a List that contains all the objects in the same iteration order
9条回答
  •  眼角桃花
    2020-11-22 05:28

    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 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).

    提交回复
    热议问题