Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine if a List is sorted in Java?

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.

like image 225
Eric Wilson Avatar asked Jun 15 '10 16:06

Eric Wilson


People also ask

Is there any sorted list in Java?

Though there is no sorted list in Java there is however a sorted queue which would probably work just as well for you. It is the java. util. PriorityQueue class.

Which collection is sorted in Java?

Collections sort is a method of Java Collections class used to sort a list, which implements the List interface. All the elements in the list must be mutually comparable. If a list consists of string elements, then it will be sorted in alphabetical order.

Is LinkedList sorted in Java?

Since LinkedList implements the java. util. List interface, you can sort the LinkedList by using the Collections. sort() method, just like you sort an ArrayList.


1 Answers

Guava provides this functionality through its Comparators class.

boolean sorted = Comparators.isInOrder(list, comparator); 

There's also the Ordering class, though this is mostly obsolete. An Ordering is a Comparator++. In this case, if you have a list of some type that implements Comparable, you could write:

boolean sorted = Ordering.natural().isOrdered(list); 

This works for any Iterable, not just List, and you can handle nulls easily by specifying whether they should come before or after any other non-null elements:

Ordering.natural().nullsLast().isOrdered(list); 

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:

Ordering.natural().reverse().isOrdered(list); 
like image 124
ColinD Avatar answered Sep 23 '22 05:09

ColinD