Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorted List in java like TreeMap or SortedSet [duplicate]

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.

like image 600
Lolly Avatar asked Nov 05 '12 16:11

Lolly


People also ask

Does sorted Set allow duplicates Java?

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.

Which collection is best for sorting in Java?

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.

Does TreeSet allow duplicates Java?

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.

Does tree Set allow duplicates?

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.


1 Answers

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.

like image 160
Bhesh Gurung Avatar answered Nov 07 '22 14:11

Bhesh Gurung