Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

One-liner to initialize list from another list

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?

like image 965
Seric Avatar asked Feb 08 '19 13:02

Seric


2 Answers

You can do it using stream and further mapping as:

return items.stream()
            .map(item -> itemToDto(item)) // map SomeItem to SomeItemDto
            .collect(Collectors.toList());
like image 82
Naman Avatar answered Oct 23 '22 09:10

Naman


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())
like image 24
Sleiman Jneidi Avatar answered Oct 23 '22 11:10

Sleiman Jneidi