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

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

    I just want to explain one more scenario like List, this list contains a few more lists of other documents like List, List, List. So the structure is

    class A {
      List documentList;
    }
    
    class Documents {
      List excels;
      List words;
      List ppt;
    }
    

    Now if you want to iterate Excel only from documents then do something like below..

    So the code would be

     List documentList = new A().getDocumentList();
    
     //check documentList as not null
    
     Optional excelOptional = documentList.stream()
                             .map(doc -> doc.getExcel())
                             .flatMap(List::stream).findFirst();
     if(excelOptional.isPresent()){
       Excel exl = optionalExcel.get();
       // now get the value what you want.
     }
    

    I hope this can solve someone's issue while coding...

提交回复
热议问题