In Java, there are many ways to maintain a Collection with elements
in sorted order.
Some collections like TreeSet store elements in the natural
ordering. In case of natural ordering we have to implement
Comparable interface for comparing the elements.
We can also maintain custom ordering by providing a custom
Comparator to a Collection.
Another option is to use the utility method Collections.sort() to sort
a List. This sorting gives nlog(n) order of performance. But if we
have to use this method multiple times then it will be costly on
performance.
Another option is to use a PriorityQueue that provides an ordered
queue. The main difference between PriorityQueue and
Collections.sort() is that PriorityQueue maintains a queue in Order
all the time, but we can only retrieve head element from queue. We
cannot access the elements of PriorityQueue in Random order.
We can use TreeSet to maintain sorted order of elements in
collection if there are no duplicate elements in collection.