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?
Share
The
Setinterface does not provide any ordering guarantees.Its sub-interface
SortedSet, and laterNavigableSet, represents a set that is sorted according to some criterion. In Java 6, there are two standard containers that implementSortedSet. They areTreeSetandConcurrentSkipListSet.In addition to the
SortedSet/NavigableSetinterfaces, there is also theLinkedHashSetclass. 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
SequencedSetto cover all three of those mentioned classes:ConcurrentSkipListSet,LinkedHashSet,TreeSet.