In Java collection which collection will doesn't allow duplicates and which also preserve insertion order of data?
-
1Does this help? http://stackoverflow.com/questions/8712469/any-implementation-of-ordered-set-in-java – vikingsteve May 10 '13 at 10:45
-
LinkedHashSet ............ – Adil Shaikh May 10 '13 at 10:46
-
Why is this marked as a duplicate of 'Is there an insertion order preserving set in Java?' This is not a duplicate of that, that question asks about Sets and Lists; this question is about all collections. – searchengine27 Apr 10 '15 at 17:21
6 Answers
LinkedHashSet
As per the documentation
This implementation differs from HashSet in that it maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is the order in which elements were inserted into the set (insertion-order)

- 17,522
- 6
- 48
- 64
LinkedHashSet
does both of them
Set set = new LinkedHashSet();

- 2,033
- 4
- 22
- 42
-
4
-
[`HashSet`](http://docs.oracle.com/javase/7/docs/api/java/util/HashSet.html) doesn't preserve insertion order. – Mark Rotteveel May 10 '13 at 10:46
-
-
Unfortunately your edit did not register as an edit so I cannot retract my downvote. You might want to consider a more substantial edit of your answer. – Mark Rotteveel May 11 '13 at 07:29
A LinkedHashSet
should fit the bill.
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. This linked list defines the iteration ordering, which is the order in which elements were inserted into the set (insertion-order).

- 67,400
- 29
- 193
- 254
You can check LinkedHashSet for this purpose.
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. This linked list defines the iteration ordering, which is the order in which elements were inserted into the set (insertion-order). Note that insertion order is not affected if an element is re-inserted into the set. (An element e is reinserted into a set s if s.add(e) is invoked when s.contains(e) would return true immediately prior to the invocation.)

- 2,285
- 5
- 32
- 38

- 384,651
- 66
- 527
- 531
Use
public class LinkedHashSet<E> extends HashSet<E>
Basically Set won't allow duplicates and
This linked list defines the iteration ordering, which is the order in which elements were inserted into the set (insertion-order)
http://docs.oracle.com/javase/6/docs/api/java/util/LinkedHashSet.html

- 120,458
- 37
- 198
- 307