-1

I have an array of Node which all have a list of Variable:

Node[] arguments; // argument[i].vars() returns List<Variable>

I would like to create a list which contains all the variables. I do it like this today:

List<Variable> allVars = new ArrayList<>();
for (Node arg : arguments) {
    allVars.addAll(arg.vars());
}

Can I do the same thing using streams?

I have tried this but it returns me a List<List<Variable>>, whereas I would like a List<Variable> with all the list's elements appended (using addAll):

List<List<Variable>> vars = Arrays.asList(arguments).stream()
                                  .map(Node::vars)
                                  .collect(Collectors.toList());
Holger
  • 285,553
  • 42
  • 434
  • 765
Gui13
  • 12,993
  • 17
  • 57
  • 104

1 Answers1

4

Use flatMap to convert the Stream<List<Variable>> to Stream<Variable> before calling collect:

List<Variable> vars = Arrays.asList(arguments).stream()
                            .map(Node::vars)
                            .flatMap(List::stream)
                            .collect(Collectors.toList());
fabian
  • 80,457
  • 12
  • 86
  • 114