如何在 ArrayList 中找到最小值以及索引号?(爪哇) [英] How to find the minimum value in an ArrayList, along with the index number? (Java)
本文介绍了如何在 ArrayList 中找到最小值以及索引号?(爪哇)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要在 Java 中获取数组列表中最小值的索引值.我的数组列表包含多个浮点数,我正在尝试想一种方法来获取最小浮点数的索引号,以便我可以在代码的其他地方使用该索引号.我是初学者,所以请不要讨厌我.谢谢!
I need to get the index value of the minimum value in my arraylist in Java. MY arraylist holds several floats, and I'm trying to think of a way I can get the index number of the smallest float so I can use that index number elsewhere in my code. I'm a beginner, so please don't hate me. Thanks!
推荐答案
您可以使用 Collections.min 和 List.indexOf:
int minIndex = list.indexOf(Collections.min(list));
如果你只想遍历列表一次(上面可能会遍历两次):
If you want to traverse the list only once (the above may traverse it twice):
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;
}
这篇关于如何在 ArrayList 中找到最小值以及索引号?(爪哇)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文