gpt4 book ai didi

java - 使用聚合代替嵌套的 for 循环

转载 作者:行者123 更新时间:2023-11-30 07:49:18 25 4
gpt4 key购买 nike

    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>Samples 的集合与另一个匹配Sample 。因此,List<Match>包含所有原始样本减去与其进行比较的样本。

问题1:聚合操作在这里有用吗?如果没有,我怎么知道他们什么时候在?

问题2:如果是,那么正确的写法是什么?

编辑: Java lesson on Aggregate Operations.

最佳答案

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));
}

关于java - 使用聚合代替嵌套的 for 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33492368/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com