Getting only required objects from a list using Java 8 Streams

前端 未结 3 2056
余生分开走
余生分开走 2021-02-14 19:12

Consider a Parent class with the attributes attrib1, attrib2 and List child with its corresponding getters and s

3条回答
  •  一个人的身影
    2021-02-14 19:20

    As I can understand you should add additional filter for child lists:

     parent.stream().filter(e -> e.getChild().stream().anyMatch(c -> c.getAttrib1() > 10)).forEach(e -> e.setChild(e.getChild().stream().filter(c -> c.getAttrib1 > 10).collect(toList())))
    

    If you have not setChild:

    • You can remove items from lists
    • Create completly new parent objects

    To remove you can use iterator:

    parent.stream().filter(e -> e.getChild().stream().anyMatch(c -> c.getAttrib1 > 10))
       .forEach(e -> {
          for(Iterator it = e.getChild().iterator(); it.hasNext();){
              Child cur = it.next();
              if(cur.getAttrib1() <= 10) it.remove();
        }
    })
    

提交回复
热议问题