Reputation: 18305
How can I easily delete duplicates in a linked list in java?
Upvotes: 0
Views: 7569
Reputation: 1451
you can use the distinct()
method of Stream. The distinct()
method works based on Stream and returns a stream that contains only a unique element. This method internally invokes the equals()
method.
duplicateElements.stream().distinct().collect(Collectors.toList());
Upvotes: 0
Reputation: 11
import java.util.*;
import java.lang.*;
class Main
{
public static void main (String[] args) throws java.lang.Exception
{
Collection<String> c = new LinkedList<String>();
c.add("JAR");c.add("BDK");c.add("JDK");c.add("JAR");c.add("WAR");c.add("APK");c.add("BDK");
c=new HashSet(c);
c=new ArrayList(c);
for(String s : c)
{
System.out.println(s);
}
}
}
Upvotes: 1
Reputation: 7471
Use a LinkedHashSet instead, and then you won't have duplicates in the first place.
Upvotes: 16
Reputation: 192015
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
.
Upvotes: 3
Reputation: 60436
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.
Upvotes: 2
Reputation: 35848
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')
Upvotes: 9