Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lambda + stream to fetch List<A> to A Single List

I have a class

class TestA {
            private List<A> listA;

      //Getters and Setters
}

and another class

class A{
       int id;
}

Now if 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 . Thanks for help in advance.

like image 865
MishraJi Avatar asked Jan 20 '26 01:01

MishraJi


1 Answers

It should look something like this...

  someList.stream()
     .map(TestA::getListA)
     .filter(testA -> testA != null && !testA.isEmpty())
     .flatMap(List::stream)
     .collect(Collectors.toList());
like image 168
Eugene Avatar answered Jan 22 '26 18:01

Eugene