如何找到 ArrayList 中的最小值以及索引号? (爪哇)

新手上路,请多包涵

我需要在 Java 的数组列表中获取最小值的索引值。我的 arraylist 有几个浮点数,我正在想办法获取最小浮点数的索引号,这样我就可以在我的代码中的其他地方使用该索引号。我是初学者,所以请不要讨厌我。谢谢!

原文由 user2130496 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 459
2 个回答

您可以使用 Collections.minList.indexOf

 int minIndex = list.indexOf(Collections.min(list));

如果只想遍历列表一次(上面可能会遍历两次):

 public static <T extends Comparable<T>> int findMinIndex(final List<T> xs) {
    int minIndex;
    if (xs.isEmpty()) {
        minIndex = -1;
    } else {
        final ListIterator<T> itr = xs.listIterator();
        T min = itr.next(); // first element as the current minimum
        minIndex = itr.previousIndex();
        while (itr.hasNext()) {
            final T curr = itr.next();
            if (curr.compareTo(min) < 0) {
                min = curr;
                minIndex = itr.previousIndex();
            }
        }
    }
    return minIndex;
}

原文由 Marimuthu Madasamy 发布,翻译遵循 CC BY-SA 3.0 许可协议

这应该使用内置函数来完成。

 public static int minIndex (ArrayList<Float> list) {
  return list.indexOf (Collections.min(list)); }

原文由 GoZoner 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题