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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With