I have seen a number of questions dealing with finding the min index. There is a solution on this related question, that uses 2 built-in functions, min and then indexOf. The problem with that approach is that it goes over the whole list twice. Is there any single built-in function for minimum/maximum indices?
2 Answers
As of Java 7, there is no such method; you would have to implement it yourself. Keep in mind that for a List, there's not necessarily one correct answer to this question, as a single object can be added to a List multiple times, or you could have multiple equal objects.
1 Comment
Here's a general solution to that problem along with a short example.
It iterates the list exactly once and returns the index of the minimal item and the minimal item itself. It is implemented to return the first index and item, if the smallest item has one or more equal items in the list.
You can adjust the immutable ListMin<T> class to your needs and adapt the code to find the maxima.
public class ListMin<T> {
final int index;
final T item;
public ListMin(int index, T item) {
this.index = index;
this.item = item;
}
public static <E extends Comparable<E>> ListMin<E> getListMin(List<E> list) {
if (list.size() == 0) {
// throw exception, do what you want.
}
ListIterator<E> it = list.listIterator();
int minIndex = 0;
E minItem = it.next(); // first is minimum
while (it.hasNext()) {
E item = it.next();
if (item.compareTo(minItem) < 0) {
minItem = item;
minIndex = it.previousIndex();
}
}
return new ListMin<E>(minIndex, minItem);
}
public static void main(String[] args) {
List<String> list = Arrays.asList("B", "A", "C");
ListMin<String> listMin = getListMin(list);
System.out.println(listMin.index);
System.out.println(listMin.item);
}
}
Listyourself and work it out.