Home > Software design >  Map a List to DTO inside map - java
Map a List to DTO inside map - java

Time:12-16

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

CodePudding user response:

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())  // perform the 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.

CodePudding user response:

With a for-loop and streams:

private Map<Integer, List<MyObjectDto>> mapNestedListToDto(Map<Integer, List<MyObject>> collection) {
    Map<Integer, List<Dto>> collectionWithDtos = new HashMap<>();
    for (Integer i : collection.keySet()) {
      List<Dto> dtos = collection.get(i).stream().map(myObject -> mappingFunction(myObject)).collect(Collectors.toList());
      mapped.put(i, dtos);
    }

    return collectionWithDtos;
}

Where mappingFunction() is the method that will actually convert an instance of MyObject to an instance of MyObjectDTO.

CodePudding user response:

You can create a new HashMap where you will put the old keys with a new values ( values will be the Dto created based on the original objects )

class Person {
String name ;
public Person(String s) {
    this.name=s;
}
@Override
public String toString() {
    // TODO Auto-generated method stub
    return name;
}
}

class PersonDto {
String name;
public PersonDto(Person p) {
    this.name=p.name "Dto";
}
@Override
public String toString() {
    // TODO Auto-generated method stub
    return name;
}
}

public class Main {
public static void main(String[] args) {
// your initial HashMap 
    Map<Integer, List<Person>> map = new HashMap<>();
    Person x =new Person("X");
    Person y =new Person("Y");
    List<Person> lst1 = new ArrayList<>();
    lst1.add(x);
    List<Person> lst2 = new ArrayList<>();
    lst2.add(y);
    
    map.put(1, lst1);
    map.put(2, lst2);
    // create a new HashMap<Integer, List<MyObjectDto>> 
    Map<Integer, List<PersonDto>> mapDto = new HashMap<>();
    // Simply use forEach 
    // in the next line instead of "new PersonDto(e)" you will put your mapping method 
    map.forEach((k,v)->{
        mapDto.put(k, v.stream().map(e-> new PersonDto(e)).collect(Collectors.toList()));
        
    });
    
    System.out.println(map);
    System.out.println(mapDto);
    
    }
}

Output :

{1=[X], 2=[Y]}

{1=[XDto], 2=[YDto]}

  • Related