How can I easily delete duplicates in a linked list in java?
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
.
Use a LinkedHashSet instead, and then you won't have duplicates in the first place.
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')
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.