我有一个PageSummary对象的ArrayList,我希望使用Java8将列表对象的值设置为我的模型类属性。
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返回字符串。
发布于 2015-09-23 22:08:56
以下是一些提示:
以下是一些教程:
https://docs.oracle.com/javase/tutorial/collections/streams/reduction.html
https://docs.oracle.com/javase/tutorial/collections/streams/index.html
发布于 2015-09-23 22:09:23
首先,您应该使用PageSummary参数创建一个Model构造函数。
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方法可以避免并发问题:)
https://stackoverflow.com/questions/32741695
复制相似问题