0

There is a simply:

public class Task{
   private String name;
   private List<Task> subtasks;
}

and a list of Task objects. How is it possible to get list of every Task as subtask by using stream(). I tried this one:

List<Task> subtasks = myTask.stream().map(x -> x.getSubtasks()).collect(Collectors.toList());

but it returns List<List<Task>>. What is the best way to join array from map() to existing result?

4
  • 2
    Can subtasks have subtasks? Commented Apr 21, 2017 at 9:47
  • 2
    Use flatMap(x -> x.getSubtasks().stream()) instead of your map() Commented Apr 21, 2017 at 9:48
  • 1
    @Holger good point, missed that it's using Task inside Task. If the rabbit hole doesn't go deeper, that duplicate should do. Commented Apr 21, 2017 at 9:48
  • 3
    @Kayaman: I added another one for the recursive case… Commented Apr 21, 2017 at 10:52

1 Answer 1

2
    List<Task> subtasks = myTask.stream()
            .flatMap(x -> x.getSubtasks().stream())
            .collect(Collectors.toList());
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.