0

Given the following entity:

public class Parent extends {
    private Long id;    
    private List<Child> children = new ArrayList<>();
}

I am attempting to learn how to use the Java 8 Stream API to flatten a List<Parent>, each containing a List<Child> and pass the stream of Child into a void method.

For example:

List<Parent> parents = //..

schedules.stream()
        .flatMap(Parent::getChildren)
        .forEach(this::invoke);

This gives the error:

Bad return type in method reference: cannot convert java.util.List< Child > to java.util.stream.Stream < ? extends R >

Samuel Philipp
  • 10,631
  • 12
  • 36
  • 56
crmepham
  • 4,676
  • 19
  • 80
  • 155
  • You flatMap to a stream. So `.flatMap(parent -> parent.getChildren().stream())` – Michael Jul 08 '19 at 20:48
  • Also I think that if the children of that first operation have any children themselves, no flat map construct will recursively invoke `getChildren`. It's one level of children only. – markspace Jul 08 '19 at 20:50

1 Answers1

2

Stream.flatMap() requires a Function which returns a Stream as parameter. You are trying to pass a Function which returns a List. Use this instead:

List<Parent> parents = ...;
parents.stream()
        .flatMap(p -> p.getChildren().stream())
        .forEach(this::invoke);

Alternatively you can use Stream.map() and Stream.flatMap():

parents.stream()
        .map(Parent::getChildren)
        .flatMap(Collection::stream)
        .forEach(this::invoke);
Samuel Philipp
  • 10,631
  • 12
  • 36
  • 56