Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the minimum value in an ArrayList, along with the index number? (Java)

Tags:

java

arraylist

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!

like image 753
user2130496 Avatar asked Apr 14 '13 03:04

user2130496


People also ask

How do you find the minimum value in an ArrayList in Java?

In order to compute minimum element of ArrayList with Java Collections, we use the Collections. min() method.

How do you find the maximum and minimum of an ArrayList in Java?

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.

How do you find the index of a number in an ArrayList?

The index of a particular element in an ArrayList can be obtained by using the method java. util. ArrayList. indexOf().


2 Answers

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; } 
like image 93
Marimuthu Madasamy Avatar answered Sep 26 '22 11:09

Marimuthu Madasamy


This should do it using built in functions.

public static int minIndex (ArrayList<Float> list) {   return list.indexOf (Collections.min(list)); } 
like image 41
GoZoner Avatar answered Sep 22 '22 11:09

GoZoner