繁体   English   中英

迭代集合,对每个项目执行操作并返回列表

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

有没有办法用java 8 Stream API做到这一点?

我需要将每个集合项转换为其他类型(dto mapping)并将所有集合作为列表返回...

就像是

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;
    }
}

先感谢您

更新#1:唯一的流对象是response.getContent()

我想你是在追求以下内容:

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

// do something with result if you need.

请注意, forEach是终端操作。 如果要对每个对象执行某些操作(例如打印它),则应使用它。 如果您想继续调用链,可能需要进一步过滤或收集到列表中,您应该使用map

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM