我有一个PageSummary对象的ArrayList,我希望使用java 8将list对象的值设置为我的Model类属性。
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){}
}
这里getAverageRating函数返回介于1-5和getContent之间的整数返回字符串。
答案 0 :(得分:3)
以下是一些提示:
以下是一些教程:
https://docs.oracle.com/javase/tutorial/collections/streams/reduction.html
https://docs.oracle.com/javase/tutorial/collections/streams/index.html
答案 1 :(得分:3)
首先,您应该使用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
方法避免了并行化时的并发问题:)