Java Collections – Why No Function for Index of Max Value?

apiapi-designcollectionsjavalist

I have been using Collections.max(list) for many projects, but I occasionally want to find the index of that maximum element. I feel silly writing a function to do this for myself in every program I write.

Why does the Collections Interface not supply a Collections.maxIndex(list)?

Best Answer

While there can be exactly one max value in a collection, there can be more than item representing that value. E.g {1, 9, 2, 9, 0} has max value of 9, represented by both elements [1] and [3].

Note that not all collections support index access; e.g. a Set<Integer> can have a meaningful maximum but accessing an element by index makes no sense in it.

Even if we limit the method to List, it would be a bit hard to come up with one method to find indices of the maximum value that is not clumsy. You could return a list of indices, but then you'd lose the value, and in some collections, e.g. linked lists, accessing an element by index is slow. Since Java does not have an easy syntax for tuples, you'd have to return a special type of object with .getValue() and .getIndices().

But I think that such an operation is just not common enough to be supported in the standard library. Finding a maximum is literally 3-4 lines of code, and tracking the index is another 1-2 lines, and there's no much room to do it wrong. If you do it a lot, you can easily put it in your own utility class.

Related Topic