How to find the minimum value in an ArrayList, along with the index number? (Java)
You can use Collections.min and 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;
}
This should do it using built in functions.
public static int minIndex (ArrayList<Float> list) {
return list.indexOf (Collections.min(list)); }
try this:
public int getIndexOfMin(List<Float> data) {
float min = Float.MAX_VALUE;
int index = -1;
for (int i = 0; i < data.size(); i++) {
Float f = data.get(i);
if (Float.compare(f.floatValue(), min) < 0) {
min = f.floatValue();
index = i;
}
}
return index;
}