java 如何在java 8中迭代对象数组列表并设置为另一个对象列表?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35790723/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to iterate List of object array and set to another object list in java 8?
提问by soorapadman
Currently I have list of object array from that array i have to Iterate and add to the list of my LatestNewsDTO
what i have done below code working but still i am not satisfy with my way . Is their any efficient way please let me know.
目前,我有来自该数组的对象数组列表,我必须迭代并添加到我LatestNewsDTO
在下面代码工作中所做的工作列表中,但我仍然不满意我的方式。他们有什么有效的方法请告诉我。
Thanks
谢谢
List<Object[]> latestNewses = latestNewsService.getTopNRecords(companyId, false, 3);
List<LatestNewsDTO> latestNewsList = new ArrayList();
latestNewses.forEach(objects -> {
LatestNewsDTO latestNews = new LatestNewsDTO();
latestNews.setId(((BigInteger) objects[0]).intValue());
latestNews.setCreatedOn((Date) objects[1]);
latestNews.setHeadLine((String) objects[2]);
latestNews.setContent(((Object) objects[3]).toString());
latestNews.setType((String) objects[4]);
latestNewsList.add(latestNews);
});
回答by Eran
Use a Stream
to map your Object[]
arrays to LatestNewsDTO
s and collect them into a List
:
使用 aStream
将Object[]
数组映射到LatestNewsDTO
s 并将它们收集到 a 中List
:
List<LatestNewsDTO> latestNewsList =
latestNewses.stream()
.map(objects -> {
LatestNewsDTO latestNews = new LatestNewsDTO();
latestNews.setId(((BigInteger) objects[0]).intValue());
latestNews.setCreatedOn((Date) objects[1]);
latestNews.setHeadLine((String) objects[2]);
latestNews.setContent(((Object) objects[3]).toString());
latestNews.setType((String) objects[4]);
return latestNews;
})
.collect(Collectors.toList());
Of course, if you create a constructor of LatestNewsDTO
that accepts the the array, the code will look more elegant.
当然,如果你创建一个LatestNewsDTO
接受数组的构造函数,代码看起来会更优雅。
List<LatestNewsDTO> latestNewsList =
latestNewses.stream()
.map(objects -> new LatestNewsDTO(objects))
.collect(Collectors.toList());
Now the LatestNewsDTO (Object[] objects)
constructor can hold the logic that parses the array and sets the members of your instance.
现在LatestNewsDTO (Object[] objects)
构造函数可以保存解析数组并设置实例成员的逻辑。
回答by soorapadman
As per the Peter Lawrey comments, This way also looks great even though i have accept the Eran answer.
根据 Peter Lawrey 的评论,即使我接受了 Eran 的回答,这种方式看起来也很棒。
I have Created the constructor with objects
我已经用对象创建了构造函数
public LatestNewsDTO(Object[] objects) {
/**set all members instance
}
And I did like this
我确实喜欢这个
List<Object[]> latestNewses = latestNewsService.getAllRecords(companyId, false);
List<LatestNewsDTO> latestNewsList = latestNewses.stream()
.map(LatestNewsDTO::new).collect(Collectors.toList());