-1

In my Java project (with Spring), I have the following Map and try to convert it to List<T>, but it returns List<List<T>> with the following stream(). So, how can I convert Map<Long, List<T>> to List<T> in Java using stream()?

final Set<UUID> set = demoMap.keySet();
final Map<UUID, List<EmployeeDTO>> employeeMap = demoService
                .getEmployees(new ArrayList<>(set));


List<EmployeeDTO> employeeList = employeeMap.values()
    .stream()
    .collect(Collectors.toList());
justice
  • 43
  • 7
  • 1
    use `flatMap(list -> list.stream())` to flatten the lists of `T`. Refer to the [docs](https://docs.oracle.com/en/java/javase/15/docs/api/java.base/java/util/stream/Stream.html#flatMap(java.util.function.Function)) – QBrute Jun 22 '21 at 13:33
  • 2
    Does this answer your question? [How can I turn a List of Lists into a List in Java 8?](https://stackoverflow.com/questions/25147094/how-can-i-turn-a-list-of-lists-into-a-list-in-java-8) – Logan Wlv Jun 22 '21 at 13:34

2 Answers2

2

Well, employeeMap.values() gives you all the values. An individual value is List<EmployeeDTO>, so a sequence of such values is Collection<List<EmployeeDTO>>. The stream variant is a Stream<List<EmployeeDTO>>.

What you want here is that you map a single element in this stream into a sequence of elements (a 1 -> 0-many mapping).

The way to do that is flatMap. This lets you map 1 item in a stream to a stream which is then 'integrated':

employeeMap
 .values()
 .stream()
 .flatMap(item -> item.stream())
 .collect(Collectors.toList());
Anton Balaniuc
  • 9,809
  • 1
  • 31
  • 52
rzwitserloot
  • 65,603
  • 5
  • 38
  • 52
1

Use flatMap to concat subLists

List<EmployeeDTO> employeeList = employeeMap.values()
    .stream()
    .flatMap(list -> list.stream())
    .collect(Collectors.toList());
Vasily Liaskovsky
  • 2,005
  • 1
  • 12
  • 30