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);
});
By using this iterator object, you can access each element in the collection, one element at a time. Obtain an iterator to the start of the collection by calling the collection's iterator() method. Set up a loop that makes a call to hasNext(). Have the loop iterate as long as hasNext() returns true.
Since Java 8, we can use the forEach() method to iterate over the elements of a list. This method is defined in the Iterable interface, and can accept Lambda expressions as a parameter.
You can iterate over an array using for loop or forEach loop. Using the for loop − Instead on printing element by element, you can iterate the index using for loop starting from 0 to length of the array (ArrayName. length) and access elements at each index.
Here is the simple, concise code to perform the task. // listOfLists is a List<List<Object>>. List<Object> result = new ArrayList<>(); listOfLists. forEach(result::addAll);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With