views:

1498

answers:

4

How can I easily delete duplicates in a linked list in java?

+2  A: 

Easily in terms of what? If it's a reasonably short list, the simplest solution is to dump it to a Set and then back to a List.

myList = new LinkedList<Whatever>(new HashSet<Whatever>(myList));

But why bother with this? If you don't want duplicates, you should be using a Set; if you only want a list so that you can keep the elements in the same order they were inserted, you can use a LinkedHashSet to get the best of both worlds: a Set that iterates predictably like a LinkedList.

Michael Myers
I agree with you not to use a List when a Set is needed. One minor detail to your code: myList = new LinkedList<Whatever>(new HashSet<Whatever>(myList)); (Since Set is an interface). Sorry for nitpicking ^^
rodion
+10  A: 

Use a LinkedHashSet instead, and then you won't have duplicates in the first place.

CoverosGene
Oooh, that's good too.
Michael Myers
That's the exact answer :) I used to make those all the time before they existed in the API, LinkedHasSets rock.
Bill K
I keep looking at that typo thinking it should have a cat behind it. "Link can has sets?"
Bill K
+1 -- nice. consider adding a link to the appropriate Javadoc.
Jason S
+8  A: 

I don't know if your requirements is to use a linked list but if not, use a Set instead of a List (you tagged the question as 'best-practices')

victor hugo
I ended up using a TreeSet instead of a plain set but it was your answer that got me to that conclusion, thanks again.
Soldier.moth
+2  A: 

Search through them and, if two represent the same thing, delete one of them.

What more do you want? Do you want advice on how to do this quickly? If that's the case, store the nodes in a hash table for easy matching when looking for duplicates.

Welbog