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?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
From the javadoc for
Set.iterator()
:And, as already stated by shuuchan, a
TreeSet
is an implemention ofSet
that has a guaranteed order: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 implementSortedSet
. They areTreeSet
andConcurrentSkipListSet
.In addition to the
SortedSet
interface, there is also theLinkedHashSet
class. It remembers the order in which the elements were inserted into the set, and returns its elements in that order.A LinkedHashSet is an ordered version of HashSet that maintains a doubly-linked List across all elements. Use this class instead of HashSet when you care about the iteration order.
LinkedHashSet is what you need.
To retain the order use
List
or aLinkedHashSet
.Iterator returned by Set is not suppose to return data in Ordered way. See this Two java.util.Iterators to the same collection: do they have to return elements in the same order?