1

I have data of which the sequence is as important as its unique elements. Meaning if something has already been added it should not be added again and the sequence must be remembered.

Set does not remember the sequence in which it was added (either hash or sort), and List is not unique.

What is the best solution to this problem?

Should one have a list and loop through it to test for uniqueness - which I'm trying to avoid? Or should one have two collections, one a List and one a Set - which I'm also trying to avoid? Or is there a different solution to this problem altogether.

kvk30
  • 1,133
  • 1
  • 13
  • 33
EarlB
  • 111
  • 2
  • 7
  • use the linked hashset – KVK Feb 09 '16 at 11:13
  • 1
    "Set does not remember the sequence in which it was added" [`LinkedHashSet`](https://docs.oracle.com/javase/7/docs/api/java/util/LinkedHashSet.html) does: "the iteration ordering ... is the order in which elements were inserted into the set (insertion-order)" – Andy Turner Feb 09 '16 at 11:13
  • Possible duplicate : http://stackoverflow.com/questions/8185090/is-there-an-insertion-order-preserving-set-that-also-implements-list – Jitin Kodian Feb 09 '16 at 11:15

4 Answers4

1

In the bellow code was your reference

 LinkedHashSet<String> al=new LinkedHashSet<String>();  
  al.add("guru");  
  al.add("karthik");  
  al.add("raja");  
  al.add("karthik");  

  Iterator<String> itr=al.iterator();  
  while(itr.hasNext()){  
   System.out.println(itr.next());  
  }  

output

guru
karthik
raja
KVK
  • 1,257
  • 2
  • 17
  • 48
0

Use LinkedHashSet. It serves as both a List and a Set. It has the uniqueness quality of a set but still remembers the order in which you inserted items to it which allows you to iterate it by order of insertion.

From the Docs:

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

Avi
  • 21,182
  • 26
  • 82
  • 121
0

You can use SortedSet or LinkedHashSet

anaxin
  • 710
  • 2
  • 7
  • 16
0

LinkedHashSet is the best possible way out

Zubair Nabi
  • 1,016
  • 7
  • 28