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?
CodePudding user response:
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
}