Skip to content
Advertisement

Map a List to DTO inside map – java

I have such collection: Map<Integer, List<MyObject>> collection I would like to map the whole list of MyObject to MyObjectDTO and return the whole map with the mapped list.

So return will be: Map<Integer, List<MyObjectDto>> collectionWithDtos

What is the easiest and quickest way? I’ve checked a couple of ways with streams but none of that produced results as I expected. Thanks

Advertisement

Answer

This is a way to go with the following simple call:

Map<Integer, List<MyObjectDto>> mappedCollection = collection.entrySet().stream()
        .collect(Collectors.toMap(
                Map.Entry::getKey, 
                e -> e.getValue()
                      .stream()
                      .map(myObject -> new MyObjectDto())  // mapping here
                      .collect(Collectors.toList())));

Basically, you want to collect it into the same-structured map with the same key. Stream the set of entries Set<Map.Entry<Integer, List<MyObject>>> and map it into a new map using Collectors.toMap(Function, Function) where:

  • Key is the same key: entry -> entry.getKey()
  • Value is the same value (List), except all MyObject objects are mapped into MyObjectDto, which can be performed with another stream.

As long as we don’t know the structures of the objects to be mapped, you have to add it by yourself to the line with a comment.

Advertisement