问题
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.
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);
});
回答1:
Use a Stream
to map your Object[]
arrays to LatestNewsDTO
s and collect them into 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.
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.
回答2:
As per the Peter Lawrey comments, This way also looks great even though i have accept the Eran answer.
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());
来源:https://stackoverflow.com/questions/35790723/how-to-iterate-list-of-object-array-and-set-to-another-object-list-in-java-8