Getting only required objects from a list using Java 8 Streams

前端 未结 3 2042
余生分开走
余生分开走 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:22

    What you need is a Stream if you want to receive all children. The following expression might do the trick:

    parents.stream().flatMap(e -> e.getChildren().stream()).filter(c -> c.getAttrib1() > 10)

    This should return all children of all parents in the list where the get attribute value is greater than 10.

    If you want to update the parents list by removing all child elements that fail a condition, you can do the following:

    parents.forEach(p -> p.getChildren().removeIf(c -> c.getAttrib1() > 10));

    This doesn't create a new list. Instead it updates the parents list itself.

提交回复
热议问题