java - 快速获取java中两个浮点数列表之和的max和maxIndex
问题描述
我正在尝试使用“轻量级流”以比我在下面管理的更快的方式计算两个列表的最大总和对:
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 列表。但在使用时,实际尺寸是事先知道的。
由于也想对最大值进行归约,并额外接收 maxIndex,因此最好使用经典循环而不是使用 Stream。
推荐阅读
- java - Android Studio 项目未打开新活动
- javascript - 使用属性值从对象数组中查找并返回对象
- javascript - 如何访问 console.log 中显示的对象属性
- python-3.x - 使用具有相同 id 但避免某些值的非缺失值填充缺失的 pandas 数据
- python - 如何从另一个python文件调用def python
- javascript - 使用 d3 或 cytoscape 渲染家谱
- javascript - 通过 app.js 连接到本地 MongoDB 服务器时遇到问题
- amazon-iam - 谁创建用户 default_user?
- python - 图像识别模型每次都猜测同一个类
- algorithm - 稳定的婚姻问题 - 空的偏好列表