user3732445
user3732445

Reputation: 241

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:)

Upvotes: 6

Views: 1561

Answers (2)

Ravindra Ranwala
Ravindra Ranwala

Reputation: 21124

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));

Upvotes: 11

Tom Hawtin - tackline
Tom Hawtin - tackline

Reputation: 147154

There is a naughty secret: write a map function for List.

Stash that little one away, and then all you need is:

WrapperDTO wrapper = new WrapperDTO(map(devices, MyClass::convertToDTO));

Don't tell the streams cool kids.

map for List should look something like:

public static <T, R> List<R> map​(
    List<T> source, Function<? super T,​? extends R> mapper
) {
    List<R> result = new ArrayList<>();
    for (T item : source) {
        result.add(mapper.apply(item));
    }
    return result;
}

Upvotes: 1

Related Questions