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.
Generally, if you need an index, you’ll have to stream over the indices. Then, the task becomes straight-forward:
a more elegant solution, which unfortunately incorporates boxing overhead is