Search code examples
javalambdajava-8refactoringcollectors

How to pass a List to a constructor of a new object using java lambda expression?


I have a problem where I want to convert a list of POJOs into DTOs and pass them into a wrapper object which is then returned. Consider this working piece of code:

List<Device> devices = dbService.getDevices(...);
List<DeviceDTO> devicesDTO = new ArrayList<DeviceDTO>();
for (Device d : devices) {
   devicesDTO.add(convertToDTO(d));
}

WrapperDTO wrapper = new WrapperDTO(devicesDTO);

I am looking for a way to rewrite this into smaller, maybe more elegant, piece of code using Java lambda expressions. This is what I have done so far. I can do the conversion from POJOs to DTOs but I am struggling to pass the list of DTOs to the constructor of a new wrapper object.

List<Device> devices = dbService.getDevices(...);
List<DeviceDTO> devicesDTO = devices.stream().map(d -> convertToDTO(d)).collect(Collectors.toList());

WrapperDTO wrapper = new WrapperDTO(devicesDTO);

How could I get it even shorter a one-liner, something like this?

WrapperDTO wrapper = devices.stream()........collect( () -> WrapperDTO:new);

Obviously, the last piece is not working but that is something I would like to achieve. Any suggestions? Thank you my friends:)


Solution

  • You may use collectingAndThen collector to solve it in one fell swoop. Use the toList collector as the downstream collector and pass the WrapperDTO::new constructor reference as the finisher function. Here's how it looks.

    final WrapperDTO wrapper = devices.stream()
        .map(d -> convertToDTO(d))
        .collect(Collectors.collectingAndThen(Collectors.toList(), WrapperDTO::new));