简体   繁体   English

使用Java 8 lambda或stream api过滤列表

[英]filter list using Java 8 lambda or stream api

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. 现在我有一个A类的列表,我想根据c.size()> 0的条件过滤它。我可以使用2 for for a过滤一个列表A和其他列表B但我想知道我可以使用java流api过滤A列表而不用for循环。

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 =
    listOfA.stream()
           .filter(a -> a.b.stream().anyMatch(b -> 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. 这假设您要将每个传递该过滤器的A实例添加到输出List一次。

Try this. 尝试这个。 items is the list which you want to filter. items是要筛选的列表。

    List<A> result = new ArrayList<>();

    result = items.stream().filter(a -> a.b.stream().filter(b -> b.c.size() > 0).count() > 0).collect(Collectors.toList());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM