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

前端 未结 6 1698
醉话见心
醉话见心 2020-12-02 20:05

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 o

6条回答
  •  失恋的感觉
    2020-12-02 20:26

    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 > int findMinIndex(final List xs) {
        int minIndex;
        if (xs.isEmpty()) {
            minIndex = -1;
        } else {
            final ListIterator 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;
    }
    

提交回复
热议问题