Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I change parameterized type in collection?

I would like to use collection in one method in my UserServiceImpl to return the list of all users which will be parameterized by UserDTO.
I have the following method:

@Override
public List<UserEntity> getUsers() {
    var usersList = userRepository.findAll();
    return usersList;
}

But I want to change it to public List<UserDTO> getUsers()... I have map method from entity to dto and vice versa:

public UserDTO mapToUserDTO(UserEntity userEntity) {
    var userDto = new UserDTO();
    var rolesEntity = userEntity.getRoles().stream()
            .map(RoleEntity::getId)
            .map(String::valueOf)
            .collect(Collectors.toList());
    userDto.setId(userEntity.getId());
    userDto.setUsername(userEntity.getUsername());
    userDto.setName(userEntity.getName());
    userDto.setSurname(userEntity.getSurname());
    userDto.setEmail(userEntity.getEmail());
    userDto.setAge(userEntity.getAge());
    userDto.setRoles(rolesEntity);
    return userDto;
}

But in this case it cannot be applied.
Could you help me out please – how can I change parametrized type from UserEntity to UserDTO in my method?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Create a stream over the list of user entities, transform each entity into a DTO via map() operation and the method you’ve shared and collect the result into a list.

public List<UserDTO> getUsers() {
    
    return userRepository.findAll().stream()
        .map(this::mapToUserDTO)       // or ClassName::mapToUserDTO
        .collect(Collectors.toList()); // or .toList() for Java 16+
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading