How to list a list of an array of objects and set a different list of objects in java 8?

Currently, I have a list of the array of objects from this array that I have to execute, and add to the list of my LatestNewsDTO what I did under the code that works, but still I am not satisfied with my path. Their effective 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); }); 
+6
source share
2 answers

Use Stream to map Object[] arrays to LatestNewsDTO and assemble 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 the LatestNewsDTO constructor that takes an 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 contain logic that parses the array and sets the members of your instance.

+7
source

According to Peter Laurie's comments, this method also looks great, although I accept Eran's answer.

I created a constructor with objects

  public LatestNewsDTO(Object[] objects) { /**set all members instance } 

And I liked it

  List<Object[]> latestNewses = latestNewsService.getAllRecords(companyId, false); List<LatestNewsDTO> latestNewsList = latestNewses.stream() .map(LatestNewsDTO::new).collect(Collectors.toList()); 
+1
source

All Articles