nKognito nKognito - 1 year ago 35
Java Question

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

Answer Source

I think you're after the following:

List<SomeObject> result = response.getContent()

// 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.