28

In Java collection which collection will doesn't allow duplicates and which also preserve insertion order of data?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Vishwanath.M
  • 6,235
  • 11
  • 42
  • 56

6 Answers6

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

sanbhat
  • 17,522
  • 6
  • 48
  • 64
22

LinkedHashSet does both of them

Set set = new LinkedHashSet();
hamid
  • 2,033
  • 4
  • 22
  • 42
10

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

Duncan Jones
  • 67,400
  • 29
  • 193
  • 254
6

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

Keith OYS
  • 2,285
  • 5
  • 32
  • 38
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
2

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

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
2

You want an ordered set, which is implemented by LinkedHashSet.

Stefano Sanfilippo
  • 32,265
  • 7
  • 79
  • 80