Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the index and max value of an array in one shot?

Given a list of integer elements, how to get the max value and it's index in one shot. If there is more than one element with same max value, returning index of any one of them is fine.

For example:

// Initialize list of integer
List<Integer> intList = Arrays.asList(5, 8, 3, 2);
// To get max value
Optional<Integer> maxVal = intList.stream().reduce(Integer::max);
// But how could I also get its index without iterating the array again?

If I have to do it only once, I could just sort the array and get the first or last one (based on sort order). However, I would like to see how we can do it without sorting.

like image 344
Srini K Avatar asked Jun 09 '15 11:06

Srini K


1 Answers

I don't think there is currently any solution that's equally as fast as iterating manually:

int maxValueIndex = 0;
Integer maxValue = null;
for (int i = 0, n = intList.size(); i < n; ++i) {
    Integer value = intList.get(i);
    if (value == null || maxValue != null && value <= maxValue)
        continue;
    maxValue = value;
    maxValueIndex = i;
}
like image 192
rustyx Avatar answered Sep 28 '22 06:09

rustyx