1

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?

1
  • 1
    I think the only alternative would be to loop over the List yourself and work it out. Commented Aug 10, 2013 at 12:17

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

yeah, that's a fair reason.
1

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);
    }
}

2 Comments

Nice implementation, +1, it was not my question though. See chrylis's answer.
@einpoklum The edit you suggested wouldn't even compile, because Constructor call must be the first statement in a constructor

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.