Lambda + stream to extract list <a> into one list

I have a class

class TestA {
            private List<A> listA;

      //Getters and Setters
}

      

and one more class

class A{
       int id;
}

      

Now if you want to collect all A into a list like below code

List<TestA> someList ; //Containing TestA
List<A> completeList = new LinkedList<A>();
for(TestA test:someList) {
  if(test.getListA() != null) {
    completeList.addAll(listA);
  }
}

      

How can I get completeList using Lambda + Stream. Thank you for your help.

+3


source to share


1 answer


It should look something like this:



  someList.stream()
     .map(TestA::getListA)
     .filter(testA -> testA != null && !testA.isEmpty())
     .flatMap(List::stream)
     .collect(Collectors.toList());

      

+4


source







All Articles