I would like to initialize List of my Dto the shortest way possible. Right now I'm using:
public List<SomeItemDto> itemsToDto(List<SomeItem> items) {
List<SomeItemDto> itemsDto = new ArrayList<SomeItemDto>();
for (SomeItem item : items) {
itemsDto.add(itemToDto(item));
}
return itemsDto;
}
Is there any way of making it a one-liner?
You can do it using stream
and further map
ping as:
return items.stream()
.map(item -> itemToDto(item)) // map SomeItem to SomeItemDto
.collect(Collectors.toList());
You can use a map
which basically applies a function to an element
List<SomeItemDto> itemsDto = items.stream().map(item -> itemToDto(item))
.collect(Collectors.toList())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With