Do we have sorted list in java just like SortedSet or TreeMap ? I have a class having one of the property as List of objects. This list has to be sorted at any time when adding or when setting it through setters (set(List list)).
Do we have any component like TreeMap for list ? Any suggestions or help will be really appreciable. Thanks in advance.
Remarks. The SortedSet<T> class does not accept duplicate elements. If item is already in the set, this method returns false and does not throw an exception.
The best general purpose or 'primary' implementations are likely ArrayList , LinkedHashMap , and LinkedHashSet . Their overall performance is better, and you should use them unless you need a special feature provided by another implementation. That special feature is usually ordering or sorting.
TreeSet cannot contain duplicate elements. The elements in a TreeSet are sorted as per their natural ordering, or based on a custom Comparator that is supplied at the time of creation of the TreeSet. TreeSet cannot contain null value. TreeSet internally uses a TreeMap to store elements.
TreeSet implements the SortedSet interface. So, duplicate values are not allowed and will be leftovers. Objects in a TreeSet are stored in a sorted and ascending order. TreeSet does not preserve the insertion order of elements but elements are sorted by keys.
The purpose of having a list is that they should maintain the order of the elements in which they were added. So, I believe there is no such List
implementation in which the elements are sorted as they are added.
You can use Collections.sort()
method to sort the list any time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With