0

I want to convert the result to List for the following code:

List<Task> taskList = projectMap.stream().map(p -> p.getProject().getTasks()).collect(Collector.toList());

but the problem is p.getProject().getTasks() is actually a Set, so I got this error

Type mismatch: cannot convert from List<Set<Task>> to List<Task>

So I also tried to return the result as a Set

Set<Task> taskList = (Set<Task>)projectMap.stream().map(p -> p.getProject().getTasks());

error

java.util.stream.ReferencePipeline$3 cannot be cast to java.util.Set

Is there anyway to convert the result to List ?

or remain the result as Set also fine, my goal is to get the list of Task which located in ProjectMap > Project > Task

Tony_Ynot
  • 155
  • 1
  • 14
  • 1
    For every project you will get `Set` so when you collect as list it became `List>`, so flat the `Set` using flatMap. Then it will be `Stream` now you can collect as list of Task . See the solution below by @Eran – Eklavya Jun 22 '20 at 11:55

1 Answers1

4

Use flatMap:

List<Task> taskList = projectMap.stream()
                                .flatMap(p -> p.getProject().getTasks().stream())
                                .collect(Collector.toList());
Eran
  • 387,369
  • 54
  • 702
  • 768