使用聚合替换嵌套的 for 循环
Using aggregates to replace nested for-loops
for (Sample i : DATA) {
for(Sample ii : DATA){
if(i.getID() == ii.getID()){
// Do nothing.
}else {
i.addMatch(new Match(ii.getID()));
}
}
}
我有一个 List<Sample>
,每个 Sample
包含一个 List<Match>
。 List<Match>
是与另一个 Sample
匹配的 Samples
的集合。因此,List<Match>
包含所有原始样本减去与之进行比较的样本。
Q1:聚合运算在这里有用吗?如果不是,我怎么知道他们什么时候?
Q2:如果是,应该怎样写才合适?
Q1: Are aggregate operations useful here? If not, how can I know when they are?
它们对您的情况有部分用处。如果您想遍历 Collection
,最好使用老式的 foreach 循环,因为它没有创建 Stream
管道的开销。但是您的内部循环非常适合 Stream
处理,因为您过滤并映射了每个元素。
Q2: If yes, what would be the appropriate way to write that?
for (Sample sample : DATA) {
DATA.stream()
.mapToInt(Sample::getId).filter(id -> id != sample.getId()).mapToObj(Match::new)
.forEach(m -> sample.addMatch(m));
}
for (Sample i : DATA) {
for(Sample ii : DATA){
if(i.getID() == ii.getID()){
// Do nothing.
}else {
i.addMatch(new Match(ii.getID()));
}
}
}
我有一个 List<Sample>
,每个 Sample
包含一个 List<Match>
。 List<Match>
是与另一个 Sample
匹配的 Samples
的集合。因此,List<Match>
包含所有原始样本减去与之进行比较的样本。
Q1:聚合运算在这里有用吗?如果不是,我怎么知道他们什么时候?
Q2:如果是,应该怎样写才合适?
Q1: Are aggregate operations useful here? If not, how can I know when they are?
它们对您的情况有部分用处。如果您想遍历 Collection
,最好使用老式的 foreach 循环,因为它没有创建 Stream
管道的开销。但是您的内部循环非常适合 Stream
处理,因为您过滤并映射了每个元素。
Q2: If yes, what would be the appropriate way to write that?
for (Sample sample : DATA) {
DATA.stream()
.mapToInt(Sample::getId).filter(id -> id != sample.getId()).mapToObj(Match::new)
.forEach(m -> sample.addMatch(m));
}