Search code examples
javajava-8java-stream

How to filter nested loops using Java 8 streams and filters?


I have two simple POJOs:

public class Parent {
    String name;
    List<Child> children = new ArrayList<>();
    void addChild(Integer age) { children.add(new Child(age)); }
}

public class Child {
    Integer age;
}

Then I generate some data, I add for parent 100 children:

List<Parent> parentList = new ArrayList<>();

Parent first = new Parent("first");
for (int i = 0; i < 100; ++i) { first.addChild(i); }
parentList.add(first);

My goal is to remove all children younger than ten:

parentList.stream().forEach(parent -> {
    parent.setChildren(getChildrenOlderThan(parent));
});

List<Child> getChildrenOlderThan10(Parent parent) {
    return parent.getChildren().stream()
        .filter(child -> child.getAge() > 10)
        .collect(Collectors.toList());
}

Finally I have list children older than ten. But I do not want to write a separate method getChildrenOlderThan.

How to get all parents with list chilrden older than ten using only the single stream?


Solution

  • There is nice method Collection.removeIf(Predicate<? super E> filter) method.

    For example:

    class Example {
    
        public static void main(String[] args){
    
            List<Parent> parentList = new ArrayList<>();
    
            // init parents with children
    
            parentList.forEach(parent -> 
                 parent.getChildren().removeIf(Example::childOlderThan10)
            );
    
        }
    
        static boolean childOlderThan10(Child child) {
            return child != null && child.getAge() > 10;
        }
    }
    

    See more: Method references, Collection.stream().forEach() vs Collection.forEach()?