Reputation: 31
I'm new to Java. I have list of dto objects and I need to convert it to the list of entities by iterating through dtos list.
I should not use model mapper or MapStruct or BeanUtils. I need to do this in the Java way, and I'm not sure how to iterate both lists at the same time.
public class AddressDto {
private String unitNo;
private String floorNo;
private String buildingName;
private String areaName;
//getters and setters
}
public class AddressEntity {
private String unitNo;
private String floorNo;
private String buildingName;
private String areaName;
//getters and setters
}
public void getAddress() {
List<AddressDto> addressDtoList=new ArrayList<>();
addressDtoList.add(new AddressDto("174", "7", "Grove", "BR"));
List<AddressEntity> addressEntityList=new ArrayList<>();
addressEntityList.add(new AddressEntity("28", "13", "Green", "Tampa"));
List<AddressEntity> addressEntityListResult=convertDtoToEntity(addressDtoList);
}
private List<AddressEntity> convertDtoToEntity(List<AddressDto> aDto) {
List<AddressEntity> newAddressEntityList = null;
for (AddressDto dto : aDto) {
//Generate and Return the newAddressEntityList by replacing Green with Grove and BR with Tampa
}
return newAddressEntityList;
}
It should be replacing Green with Grove and BR with Tampa only. Remaining object such as "28", "13" should be unchanged.
Upvotes: 3
Views: 15310
Reputation: 2776
You have received a great answer, but here's another way to do it:
private List<AddressEntity> convertDtoToEntity(List<AddressDto> aDto) {
List<AddressEntity> newAddressEntityList = new ArrayList<>();
for (AddressDto dto : aDto) {
AddressEntity addressEntity = new AddressEntity(
dto.getUnitNo(),
dto.getFloorNo(),
dto.getBuildingName(),
dto.getAreaName()
);
newAddressEntityList.add(addressEntity);
}
return newAddressEntityList;
}
Upvotes: 1
Reputation: 1889
Nowadays, the Java way is to use Stream API.
Here's a snippet on how to convert a List<AddressDto>
to a List<AddressEntity>
private static List<AddressEntity> convertDtoToEntity(List<AddressDto> aDto) {
return aDto.stream()
.map(dto -> new AddressEntity(dto.getUnitNo(), dto.getFloorNo(), dto.getBuildingName(), dto.getAreaName()))
.collect(Collectors.toList());
}
The function passed to the .map
method is the one responsible of converting each element of the stream from AddressDto to AddressEntity.
Upvotes: 4