In Java there are the SortedSet and SortedMap interfaces. Both belong to the Java Collections framework and provide a sorted way to access the elements.
However, in
Since all lists are already "sorted" by the order the items were added (FIFO ordering), you can "resort" them with another order, including the natural ordering of elements, using java.util.Collections.sort()
.
EDIT:
Lists as data structures are based in what is interesting is the ordering in which the items where inserted.
Sets do not have that information.
If you want to order by adding time, use List
. If you want to order by other criteria, use SortedSet
.
Consider using indexed-tree-map . It's an enhanced JDK's TreeSet that provides access to element by index and finding the index of an element without iteration or hidden underlying lists that back up the tree. The algorithm is based on updating weights of changing nodes every time there is a change.
For any newcomers, as of April 2015, Android now has a SortedList class in the support library, designed specifically to work with RecyclerView
. Here's the blog post about it.
Set and Map are non-linear data structure. List is linear data structure.
The tree data structure SortedSet
and SortedMap
interfaces implements TreeSet
and TreeMap
respectively using used Red-Black tree implementation algorithm. So it ensure that there are no duplicated items (or keys in case of Map
).
List
is already maintains an ordered collection and index-based data structure, trees are no index-based data structures.Tree
by definition cannot contain duplicates.List
we can have duplicates, so there is no TreeList
(i.e. no SortedList
).java.util.Collections.sort()
. It sorts the specified list into ascending order, according to the natural ordering of its elements.Because the concept of a List is incompatible with the concept of an automatically sorted collection. The point of a List is that after calling list.add(7, elem)
, a call to list.get(7)
will return elem
. With an auto-sorted list, the element could end up in an arbitrary position.
SortedList
Though it took a while, Java 8 does have a sorted List
.
http://docs.oracle.com/javase/8/javafx/api/javafx/collections/transformation/SortedList.html
As you can see in the javadocs, it is part of the JavaFX collections, intended to provide a sorted view on an ObservableList.
Update: Note that with Java 11, the JavaFX toolkit has moved outside the JDK and is now a separate library. JavaFX 11 is available as a downloadable SDK or from MavenCentral. See https://openjfx.io