One-liner to initialize list from another list
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 are open to using a third-party library, you can use the ListIterate
utility from Eclipse Collections with any List
.
List<SomeItemDto> itemsDto = ListIterate.collect(items, this::itemToDto);
If items was a MutableList
from Eclipse Collections, you could use the API directly on the list as follows:
List<SomeItemDto> itemsDto = items.collect(this::itemToDto);
Note: I am a committer for Eclipse Collections.