How to set class attributes from a list of objects in Java 8

I have one ArrayList object of a PageSummary object and I want to set the value from a list object to my model class attributes using java 8.

public class XXXX {
for(PageSummary ps : pageSummaryList){
model = new Model();
model.setName(ps.getName());
model.setContent(getContent(ps.getName()));
model.setRating(getAverageRating(ps.getName()));
modelList.add(model);
}                   

private String getContent(String sopName){} 

private AverageRatingModel getAverageRating(String sopName){}
}

Here, the getAverageRating function returns an integer between 1-5 and the getContent string returned.

+4
source share
2 answers

Here are some suggestions:

  • create a PageSummary stream from a list
  • map from PageSummary to Model
  • assemble the Model object

Here are some guides:

https://docs.oracle.com/javase/tutorial/collections/streams/reduction.html

https://docs.oracle.com/javase/tutorial/collections/streams/index.html

+3
source

Model PageSummary.

public Model(PageSummary ps) {
    this.setSopName(ps.getName());
    this.setSopContent(getContent(ps.getName(), clientCode, context, httpcliet));
    this.setAverageRating(getAverageRating(ps.getName(), clientCode, context, httpclient));
}

:

for (PageSummary ps : pageSummaryList) {
    ModelList.add(new Model(ps));
}

Stream API:

// This solution is thread-safe only if ModelList is thread-safe
// Be careful when parallelizing  :)
pageSummaryList.stream().map(Model::new).forEach(ModelList::add);

// A thread-safe solution using Stream::collect()
List<Model> models = pageSummaryList.stream()
                                    .parallel() // optional :)
                                    .map(Model::new)
                                    .collect(Collectors.toList());
ModelList::addAll(models); // I suppose you don't need us to implements this one!

Alexis C. , collect concurrency :)

+3

Source: https://habr.com/ru/post/1608679/


All Articles