Reputation: 241
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
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
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