IMO, from what I'm seeing, the complexity of checking this is as bad as performing the sort for a second time, and I understand people are short circuiting with returns if it is not sorted, but if the List is actually sorted, then the entire length will be traversed..., I'd argue to just let the code continue as if the List was sorted, and let the code itself figure out if it is or not.
I would recommend placing an Error detailing why the specific line that will fail is doing so because its collection is not reversed/ordered etc...
eg.
the line detachTailIndex.run()
will give a NullPointerException(),
if (fromReversedMethod && detachTailIndex == null) {
throw new NullPointerException("detachTailIndex was null. \n
Reason: The List<> is required to be reversed before submission")
}
Or if your plan is to use a conditional for when sorted or not the you can use the null to verify if it is sorted and choose the other option.
If there is no other option, then using the other responses are ok.
Here is another example:
int key = entry.getKey();
List<Integer> shouldBeReversed = entry.getValue();
try {
//If all entries need to be iterated better place them inside the Try-Catch
updateBatch(key,
xes -> {
for (int rowIndex : shouldBeReversed
) {
xes.remove((int) rowIndex); // will return an IndexOutOfBoundsException if not sorted in reverse
}
return xes;
}
);
} catch (IndexOutOfBoundsException e) {
throw new IndexOutOfBoundsException(e.getMessage() + "\n" +
"Reason: Batch indexes (Entry's value \"List<Integer>\") should be sorted in reverse order before submission");
}
if conditional is required (on sorted, or on not sorted) then the
catch()
body could be used as a "not sorted" option.
Of course this is very very case specific, but seems that checking for a sorting order just to get a boolean seems too much (?) specially on iterations.