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

后端 未结 9 778
春和景丽
春和景丽 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:07

    An expansion on Eran's answer that was the top answer, if you have a bunch of layers of lists, you can keep flatmapping them.

    This also comes with a handy way of filtering as you go down the layers if needed as well.

    So for example:

    List>>>>> multiLayeredList = ...
    
    List objectList = multiLayeredList
        .stream()
        .flatmap(someList1 -> someList1
            .stream()
            .filter(...Optional...))
        .flatmap(someList2 -> someList2
            .stream()
            .filter(...Optional...))
        .flatmap(someList3 -> someList3
            .stream()
            .filter(...Optional...))
        ...
        .collect(Collectors.toList())
    
    
    

    This is would be similar in SQL to having SELECT statements within SELECT statements.

    提交回复
    热议问题