filter list using Java 8 lambda or stream api

  • A+

My class structure -

class A {     List<B> bList; }  class B {    List<C> cList; } 

Now i have a list of class A and i want to filter it based on condition that c.size() > 0. I can filter it using 2 for loop one for list A and other for list B but i want to know can i filter list of A using java stream api without for loop.

My current code (updated code) -

List<A> result = = new ArrayList<>(); for (A a : aList) {    List<B> tempBList = = new ArrayList<>();    for (B b : a.getBList) {        if (b.getCList.size() > 0) {           tempBList.add(b);        }    }     if (tempBList.size() > 0) {        a.setBList(tempBList);        result.add(a);    } } 


Yes, you can:

List<A> result =            .filter(a -> -> b.c.size() > 0))            .collect(Collectors.toList()); 

This is assuming you want to add each instance of A that passes that filter to the output List once.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: