-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
  • 267,107
  • 35
  • 402
  • 715
Gui13
  • 12,595
  • 16
  • 53
  • 101

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
  • 72,938
  • 12
  • 79
  • 109