Java 8 collecting the list that is already present in object

醉酒当歌 提交于 2021-02-17 03:44:07

问题


I was just searching for better way to handle this scenario using java 8 streams. Object A has list of object b. What I get is a list of object A (List). I need to stream through list of object A and get all the listB's in each of the object A as a one single list.

class A {
    List<B> listB
}

I have tried the below way it throws compilation

List<A> as = someObject.getAs();
List<B> listofBs = as.stream().map(in -> in.getListB()).collect(Collectors.toList());

回答1:


To get a single list of all B's, you should use flatMap as:

List<B> listOfBs = listOfAs.stream()
        .flatMap(a -> a.getListB().stream())
        .collect(Collectors.toList());



回答2:


Class A{
  List<B> listB
};
List<A> listA;
listA.stream().map(
 a->{
  //some code for A
  a.ListB.stream().map(
   b->{
    // some code for B
  })
});

may be help you



来源:https://stackoverflow.com/questions/56014710/java-8-collecting-the-list-that-is-already-present-in-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!