soorapadman
soorapadman

Reputation: 4509

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

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

Upvotes: 10

Views: 50024

Answers (2)

soorapadman
soorapadman

Reputation: 4509

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()); 

Upvotes: 0

Eran
Eran

Reputation: 393841

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.

Upvotes: 18

Related Questions