Map just ONE object to another (DTO) with Java8

Viewed 8240

can you tell me if exist some pretty way to map one entity object to another dto object? When I needed convert List<ObjEntity> to List<ObjDTO> I created that function:

public class Converter {
public static Function<ObjEntity, ObjDTO> MYOBJ_ENTITY_TO_DTO = objEntity -> {
    ObjDTO dto = new ObjDTO();

    dto.setId(objEntity.getId());
    dto.setName(objEntity.getName());
    dto.setNote(objEntity.getNote());
    // ...

    return dto;
    };
}

and I use it like this:

List<ObjDTO> dtos =  objEntitiesList.stream().map(Converter.MYOBJ_ENTITY_TO_DTO).collect(Collectors.toList());

But what if I need convert just ONE object? Should I use that function MYOBJ_ENTITY_TO_DTO for that and how? Or what is the best practice? Yes, I can do classical function in Converter class like that:

public static ObjEntity dtoToEntity(ObjDTO dto) {
   // map here entity to dto and return entity
}

but it is old style. Exist some new practice in java 8? Something similar like my example for list by lambda?

1 Answers
ObjDTO dto = MYOBJ_ENTITY_TO_DTO.apply(entity);

I see the other way around more often: instead of MYOBJ_ENTITY_TO_DTO, define entityToDto as a method and use

List<ObjDTO> dtos =  objEntitiesList.stream().map(Converter::entityToDto).collect(Collectors.toList());

for lists.

Related