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.

3
  • use the linked hashset Commented Feb 9, 2016 at 11:13
  • 1
    "Set does not remember the sequence in which it was added" LinkedHashSet does: "the iteration ordering ... is the order in which elements were inserted into the set (insertion-order)" Commented Feb 9, 2016 at 11:13
  • Possible duplicate : stackoverflow.com/questions/8185090/… Commented Feb 9, 2016 at 11:15

4 Answers 4

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
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

0

You can use SortedSet or LinkedHashSet

Comments

0

LinkedHashSet is the best possible way out

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.