2

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?

Kamil Nękanowicz
  • 6,254
  • 7
  • 34
  • 51

2 Answers2

6

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()?

Anatoly Shamov
  • 2,608
  • 1
  • 17
  • 27
Andrii Abramov
  • 10,019
  • 9
  • 74
  • 96
1

You may inline the method getChildreanOlderThan like this:

parentList.stream().forEach(parent -> {
    parent.setChilds(parent.getChildren().stream()
            .filter(child -> child.getAge() > 10)
            .collect(Collectors.toList()));
    });
Harmlezz
  • 7,972
  • 27
  • 35
  • 2
    Sure, it will work. But some suggestions: `stream()` on `parentList` is useless here, This kind of filtering is harder to read and maintain. – Andrii Abramov Dec 23 '16 at 10:11
  • @Andrii I as well like your solution more than mine. But could you explain why the `stream()` on `parentList` is useless? Does it not fulfill the goal? Do I have a bug in the implementation? – Harmlezz Dec 23 '16 at 10:15
  • See please: http://stackoverflow.com/questions/23218874/what-is-difference-between-collection-stream-foreach-and-collection-foreach – Andrii Abramov Dec 23 '16 at 10:16