How to iterate List of object array and set to another object list in java 8?

天大地大妈咪最大 提交于 2020-07-06 09:54:08

问题


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 LatestNewsDTOs 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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!