Creating TypeMap to use property mapping and converter class

This commit is contained in:
Sasa M
2020-04-29 21:55:30 +02:00
committed by Sasa M
parent 8d7d98a144
commit 9bf7546d42
4 changed files with 43 additions and 49 deletions
@@ -6,7 +6,7 @@ import java.util.List;
import java.util.stream.Collectors;
/**
* This is a helper class that contains method for generic mapping of the users list.
* This is a helper class that contains method for custom mapping of the users list.
* Initially, an instance of ModelMapper was created.
*
* @author Sasa Milenkovic
@@ -1,37 +0,0 @@
package com.baeldung.modelmapper;
import org.modelmapper.AbstractConverter;
import org.modelmapper.Converter;
import org.modelmapper.PropertyMap;
import java.util.List;
import java.util.stream.Collectors;
/**
* UserPropertyMap class instantiates the converter to map the data from the UserList to the UsersLisDTO.
* In the configuration method, we call a converter to do the mapping.
*
* @author Sasa Milenkovic
*/
public class UserPropertyMap extends PropertyMap<UserList, UserListDTO> {
Converter<List<User>, List<String>> converter = new AbstractConverter<List<User>, List<String>>() {
@Override
protected List<String> convert(List<User> users) {
return users
.stream()
.map(User::getUsername)
.collect(Collectors.toList());
}
};
@Override
protected void configure() {
using(converter).map(source.getUsers(), destination.getUsernames());
}
}
@@ -0,0 +1,23 @@
package com.baeldung.modelmapper;
import org.modelmapper.AbstractConverter;
import java.util.List;
import java.util.stream.Collectors;
/**
* UsersListConverter class map the property data from the list of users into the list of user names.
*
* @author Sasa Milenkovic
*/
public class UsersListConverter extends AbstractConverter<List<User>, List<String>> {
@Override
protected List<String> convert(List<User> users) {
return users
.stream()
.map(User::getUsername)
.collect(Collectors.toList());
}
}