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!
In order to compute minimum element of ArrayList with Java Collections, we use the Collections. min() method.
Then the length of the ArrayList can be found by using the size() function. After that, the first element of the ArrayList will be store in the variable min and max. Then the for loop is used to iterate through the ArrayList elements one by one in order to find the minimum and maximum from the array list.
The index of a particular element in an ArrayList can be obtained by using the method java. util. ArrayList. indexOf().
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)); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With