Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Set retain order?

Tags:

java

sorting

set

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?

like image 942
user840930 Avatar asked May 25 '12 10:05

user840930


People also ask

Does Set retain order Java?

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).

Does Set retain 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.

Does HashSet in Java maintain insertion order?

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.

Is Set always sorted Java?

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.


2 Answers

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.

like image 111
NPE Avatar answered Oct 03 '22 06:10

NPE


LinkedHashSet is what you need.

like image 39
xiaofeng.li Avatar answered Oct 03 '22 05:10

xiaofeng.li