Why does Collections.sort()
apply only for List
s and not for Set
s? Is there any particular reason?
Yes, the Collections. sort methods are only for lists. You can't sort HashSet , but a TreeSet is automatically sorted as you add items, and LinkedHashSet is sorted by insertion order. Show activity on this post.
How does the Sort Method in the Collection Sort Work? Whenever we need to sort the values in a collection, this “sort” method transfers control to the compare method in the class. The compare method then returns some values based on the comparison. It returns 0 if both the objects are equal.
sort() vs Collections.sort works for arrays which can be of primitive data type also.
Collections sort is a method of Java Collections class used to sort a list, which implements the List interface. All the elements in the list must be mutually comparable. If a list consists of string elements, then it will be sorted in alphabetical order.
Most (but not all) Set
implementations do not have a concept of order, so Collections.sort
does not support them as a whole. If you want a set with a concept of order, you can use something like a TreeSet
:
A
NavigableSet
implementation based on aTreeMap
. The elements are ordered using their natural ordering, or by aComparator
provided at set creation time, depending on which constructor is used.
Or a LinkedHashSet
:
Hash table and linked list implementation of the
Set
interface, with predictable iteration order. This implementation differs fromHashSe
t in that it maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is the order in which elements were inserted into the set (insertion-order)
A Set, by definition, has no order.
A Set
is not a List
. While a List
, by contract, is supposed to retain insertion order (otherwise, methods such as .get(someindex)
would not make any sense), this is not the case for a Set
. You have no method to get an element at a particular index in a Set
! Neither do you have methods to insert at a particular position etc.
More specifically, the ordering of Set
is undefined; however, implementations of Set
can add ordering constraints.
For instance:
LinkedHashSet
retains insertion ordering;TreeSet
maintains natural ordering of its elements, either because its elements implement Comparable
, or because you supply a Comparator
.If you sorted a LinkedHashSet
, you would break its insertion ordering guarantee!
A set is not ordered. You can use SortedSet. Or you can create a List from the set and sort it.
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