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!
解决方案
int minIndex = list.indexOf(Collections.min(list));
If you want to traverse the list only once (the above may traverse it twice):
public static > int findMinIndex(final List xs) {
int minIndex;
if (xs.isEmpty()) {
minIndex = -1;
} else {
final ListIterator 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;
}