首页 > 解决方案 > 快速获取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));

标签: javaandroidjava-streamlightweight-stream-api

解决方案


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。


推荐阅读