Does a Java Set retain order? A method is returning a Set to me and supposedly the data is ordered but iterating over the Set, the data is unordered. Is there a better way to manage this? Does the method need to be changed to return something other than a Set?
The Set
interface does not provide any ordering guarantees.
Its sub-interface SortedSet
, and later NavigableSet
, represents a set that is sorted according to some criterion. In Java 6, there are two standard containers that implement SortedSet
. They are TreeSet
and ConcurrentSkipListSet
.
In addition to the SortedSet
/NavigableSet
interfaces, there is also the LinkedHashSet
class. It remembers the order in which the elements were inserted into the set, and returns its elements in that order.
In Java 21+, with sequenced collections added, we have the super-interface of SequencedSet
to cover all three of those mentioned classes: ConcurrentSkipListSet
, LinkedHashSet
, TreeSet
.