You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取Arrays.stream(array).min()对应的数组最小值索引?

获取Java数组中最小值对应的索引

你当前的代码已经能正确获取数组的最小值,但Java没有直接的getIndexOf方法可以直接拿到最小值的索引,以下是几种可行的实现方式:

方法一:遍历数组查找(直观易懂)

基于你现有的代码,拿到最小值后直接遍历数组匹配,找到对应的索引:

import java.util.Arrays;
class getIndexOfMin {
    public static void main(String[] args) {
        double arr[] = {263.5, 393.75, 5.0, 289.75};
        
        // 获取数组最小值
        double min = Arrays.stream(arr).min().getAsDouble();
        
        // 遍历数组查找最小值的索引
        int minIndex = -1;
        for (int i = 0; i < arr.length; i++) {
            // 若涉及浮点数计算,建议用Double.compare或差值判断替代==
            if (arr[i] == min) {
                minIndex = i;
                break; // 找到第一个匹配的最小值就终止遍历
            }
        }
        
        System.out.println("最小值:" + min);
        System.out.println("最小值对应的索引:" + minIndex);
    }
}

方法二:用流一次性获取索引(更高效)

无需先单独获取最小值,直接通过IntStream处理索引,一步到位找到最小值对应的索引:

import java.util.Arrays;
import java.util.OptionalInt;

class getIndexOfMin {
    public static void main(String[] args) {
        double arr[] = {263.5, 393.75, 5.0, 289.75};
        
        // 生成索引流,通过reduce筛选出最小值对应的索引
        OptionalInt minIndex = IntStream.range(0, arr.length)
                .reduce((i, j) -> arr[i] < arr[j] ? i : j);
        
        // 处理空数组的情况(非空数组可直接getAsInt)
        if (minIndex.isPresent()) {
            int index = minIndex.getAsInt();
            System.out.println("最小值对应的索引:" + index);
            System.out.println("最小值:" + arr[index]);
        }
    }
}

注意事项

  • 上述两种方法默认返回第一个出现的最小值的索引,如果需要获取所有最小值的索引,可将匹配的索引存入集合而非直接break。
  • 若数组元素是计算产生的浮点数,避免直接用==比较,建议使用Double.compare(arr[i], min) == 0,或判断Math.abs(arr[i] - min) < 1e-9(根据精度需求调整阈值)来规避浮点数精度问题。

内容的提问来源于stack exchange,提问作者fujitsu fiji

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 18:20:58