I would like a method that takes a List<T> where T implements Comparable and returns true or false depending on whether the list is sorted or not.
What is the best way to implement this in Java? It’s obvious that generics and wildcards are meant to be able to handle such things easily, but I’m getting all tangled up.
It would also be nice to have an analogous method to check if the list is in reverse order.
Guava provides this functionality through its Comparators class.
There’s also the Ordering class, though this is mostly obsolete. An
Orderingis aComparator++. In this case, if you have a list of some type that implementsComparable, you could write:This works for any
Iterable, not justList, and you can handlenulls easily by specifying whether they should come before or after any other non-nullelements:Also, since you mentioned that you’d like to be able to check for reverse order as well as normal, that would be done as: