Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java list that automatically sorts elements as I add them [duplicate]

Possible Duplicate:
sorted collection in java

I'm wondering if there is a built-in class in Java that lets me add elements that are automatically sorted. Sorting should preserve add order if two elements are ranked the same. I think it would be like a priority queue but shouldn't "pop" the elements, I want them to stay in the list.

Obviously I could implement this myself but I'd rather use something implemented in the Java language (less bug testing / would be good to know for future projects too instead of importing my own code).

I would also be interested in third party source if there isn't anything like this in the language.

like image 535
Ciph3rzer0 Avatar asked Aug 17 '11 18:08

Ciph3rzer0


People also ask

Which Java set data structure sorts the data automatically?

There are two data structures in the standard Java collections package that sort automatically: the interfaces SortedSet and SortedMap , which are implemented by TreeSet and TreeMap , respectively.

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 would you use to keep sorted collection of unique objects?

If you just want to sort a list, use any kind of List and use Collections. sort(). If you want to make sure elements in the list are unique and always sorted, use a SortedSet.


1 Answers

It seems SortedList this would work

This class implements a sorted list. It is constructed with a comparator that can compare two objects and sort objects accordingly. When you add an object to the list, it is inserted in the correct place. Object that are equal according to the comparator, will be in the list in the order that they were added to this list. Add only objects that the comparator can compare.

like image 60
jmj Avatar answered Nov 01 '22 01:11

jmj