(); // -6ren">
gpt4 book ai didi

java - 快速获取java中两个浮点列表之和的max和maxIndex

转载 作者:行者123 更新时间:2023-11-29 06:49:07 24 4
gpt4 key购买 nike

我正在尝试以比我在下面管理的方法更快的方式计算两个列表的最大和对,使用 "lightweight streams" :

 List<Float> pairsSum = new ArrayList<>();
// Get the list with all the sums
Stream.range(0, list1.size())
.forEach(i -> pairsSum.add(list1.get(i) + list2.get(i)));
// Get the index of the max pair
maxIndex = pairsSum.indexOf(Stream.of(pairsSum).max(Double::compare).orElse(0f));

最佳答案

List<Float> pairsSum = new ArrayList<>(repLeftForces.size());
// Get the list with all the sums
int maxIndex = -1;
float max = 0F;
for (int i =0; i < repLeftForces.size(); ++i) {
float sum = list1.get(i) + list2.get(i);
//pairsSum.add(sub);
if (maxIndex == -1 || sum > max) {
maxIndex = i;
max = sum;
}
}

实际上不需要 pairsSum 列表。但是在使用的时候,实际尺寸是事先知道的。

因为人们也想为最大值做一个reduce,并额外接收 maxIndex,最好是经典循环而不是使用 Stream。

关于java - 快速获取java中两个浮点列表之和的max和maxIndex,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55496811/

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