Iterate through the collection, take actions on each item, and return as a list

Is there a way to do this using the java 8 Stream API?

I need to convert each element of a collection to a different type (dto mapping) and return the whole 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 thread object is response.getContent()

+3


source to share


1 answer


I think you do the following:

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

// do something with result if you need.

      



Note that this forEach

is a terminal operation. You should use it if you want to do something with each object (for example, print it out). If you want to continue the chain of calls, perhaps continue filtering or collect in a list, you should use map

.

+4


source







All Articles