How can I easily delete duplicates in a linked list in java?
-
I left out some details, sorry, the data structure needed to be duplicate free, sorted, and able to have an iterator.Bobby– Bobby2009-05-29 16:22:22 +00:00Commented May 29, 2009 at 16:22
-
1A SortedSet like TreeSet will do all this.Peter Lawrey– Peter Lawrey2009-06-01 20:58:49 +00:00Commented Jun 1, 2009 at 20:58
-
@Peter Lawrey - Thanks, for the comment, I did discover the TreeSet data structure a couple days ago and it is exactly what I needed.Bobby– Bobby2009-06-02 03:29:22 +00:00Commented Jun 2, 2009 at 3:29
6 Answers
Use a LinkedHashSet instead, and then you won't have duplicates in the first place.
3 Comments
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')
1 Comment
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.
1 Comment
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);
}
}
}