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?
Set is an unordered collection, it doesn't maintain any order. There are few implementations of Set which maintains the order such as LinkedHashSet (It maintains the elements in insertion order).
A Set will not allow duplicate values. And LinkedHashSet will preserve insertion order. Hash table and linked list implementation of the Set interface, with predictable iteration order. This implementation differs from HashSet in that it maintains a doubly-linked list running through all of its entries.
HashSet does not provide any method to maintain the insertion order. Comparatively, LinkedHashSet maintains the insertion order of the elements. We can not predict the insertion order in HashSet, but we can predict it in LinkedHashSet. The LinkedHashSet extends the HashSet, so it uses a hashtable to store the elements.
No, HashSet is not sorted - or at least, not reliably. You may happen to get ordering in some situations, but you must not rely on it.
The Set
interface does not provide any ordering guarantees.
Its sub-interface SortedSet
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
interface, 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.
LinkedHashSet is what you need.
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