Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate through collection, perform action on each item and return as List

Is there any way to do it with java 8 Stream API?

I need to transform each item of collection to other type (dto mapping) and return all set as a list...

Something like

Collection<OriginObject> from = response.getContent();
DtoMapper dto = new DtoMapper();    
List<DestObject> to = from.stream().forEach(item -> dto.map(item)).collect(Collectors.toList());

public class DtoMapper {
    public DestObject map (OriginObject object) {
        return //conversion;
    }
}

Thank you in advance

Update #1: the only stream object is response.getContent()

like image 836
nKognito Avatar asked May 11 '15 08:05

nKognito


1 Answers

I think you're after the following:

List<SomeObject> result = response.getContent()
                                  .stream()
                                  .map(dto::map)
                                  .collect(Collectors.toList());

// do something with result if you need.

Note that forEach is a terminal operation. You should use it if you want to do something with each object (such as print it). If you want to continue the chain of calls, perhaps further filtering, or collecting into a list, you should use map.

like image 50
aioobe Avatar answered Sep 28 '22 05:09

aioobe