转换这个嵌套的迭代是我的想法,有人可以将此转换为并行流吗?我希望能够检查符合我的每个帐户小组成员标准的作业。我刚刚切换到java 8,并且正在努力围绕利用并行流来预先形成这种聚合的最佳方式。
for(Iterator<BasicDBObject> iterator = members.iterator(); iterator.hasNext();) {
BasicDBObject member = iterator.next();
//if the member doesn't have a valid assignment remove them.
boolean memberContainsValidAssignment = false;
BasicDBObject role = member.get("accountTeamRole") == null ? null : (BasicDBObject) member.get("accountTeamRole");
if (accTeamRoleCodes != null && !accTeamRoleCodes.contains(role.get("code"))) {
iterator.remove();
continue;
}
List<BasicDBObject> assignments = member.get("assignments") == null ? new ArrayList<>() : (List) member.get("assignments");
for (Iterator<BasicDBObject> assignIterator = assignments.iterator(); assignIterator.hasNext(); ) {
BasicDBObject assignment = assignIterator.next();
Date endDate = (Date) assignment.get("assignmentValidToDate");
Date startDate = (Date) assignment.get("assignmentValidFromDate");
if(startDate == null){//this is junk, should have never been allowed.
LOGGER.warn("There's no start date for this assignment. {}", assignment.toString());
assignIterator.remove();
continue;
}
//1. open ended assignment, it lives on forever. 2.falls in between active date.
else if(endDate == null ||(activeDate.after(startDate) && activeDate.before(endDate))){
LOGGER.debug("adding an assignment. {}", assignment.toString());
memberContainsValidAssignment = true;
convertDatesToString(assignment);
continue;
}
}
if(!memberContainsValidAssignment){
iterator.remove();
}
}
答案 0 :(得分:1)
以下是将代码转换为使用流的镜头。请检查过滤条件的详细信息。
List<BasicDBObject> invalidAssignments = members.stream()
.filter(member -> accTeamRoleCodes == null ||
member.get("accountTeamRole") == null ||
accTeamRoleCodes.contains(member.get("accountTeamRole").get("code"))
)
.flatMap(member -> member.get("assignments").stream())
.filter(assignment -> (Date) assignment.get("assignmentValidFromDate") != null &&
((Date) assignment.get("assignmentValidToDate") != null ||
(activeDate.after((Date)assignment.get("assignmentValidFromDate")) &&
activeDate.before((Date)assignment.get("assignmentValidToDate"))))
)
.collect(Collectors.toList());
要使事情平行,只需使用members.parallelStream
代替members.stream
。