Java: Remove Duplicates In Vector
Posted by admin on
February 13, 2009
Either you do this
Vector newVect = new Vector(new LinkedHashSet(originalVect));
or this, if you do not need a new Vector object created
Collection noDup = new LinkedHashSet(emails); emails.clear(); emails.addAll(noDup);











12 Responses to “Java: Remove Duplicates In Vector”
Great solution!
Thanks a lot!!!!
By Nicolò on Nov 25, 2009
Thanks a lot, I spent several hours trying to code a method for removing duplicates from a Vector containing Strings.
Good work!!
By Nono L. on Jan 7, 2010
This worked great! However, I have never used LinkedHashSet and don’t quite understand what is going on in option 1 above. Could you further explain? Thanks!!
By Brandon on Jan 18, 2010
a LinkedHashedSet does not allow duplicates so you can just pass that as the parameter when you instantiate a Vector object and voila! no more duplicates in the Vector
By tech on Jan 18, 2010
Thanks for your quick response! Ok I did this once and it worked fine, and it still is working fine. However I am using Method 1 above to remove duplicates from a second Vector that I am using but using LinkedHashSet is not removing them. What exactly does LinkedHashSet look for when determining if an element is a duplicate or not? Thanks!
By Brandon on Jan 20, 2010
hi brandon. in the first method, the originalVect’s contents are of String. just like how the equals() method works in the String class could be the same way how LinkedHashSet checks for duplicates and removes them if found
By tech on Jan 20, 2010
Hmm..well my both of my Vector contains Java objects and the first time I used this it worked, but I can’t figure out why it won’t work for my 2nd Vector of objects. I’m going to have to debug a little more, but any other help you could provide would be awesome. Thanks!
By Brandon on Jan 20, 2010
i have used that code if my Vector contains String. i have not tried it on other types of objects so i cannot verify.
By tech on Jan 20, 2010
This is a very exciting post, I was looking for this knowledge. Just so you know I found your website when I was researching for blogs like mine, so please check out my site sometime and leave me a comment to let me know what you think.
By Young Jarnesky on Apr 9, 2010
Question and answer:
We can duplicate and r remove vector by using in the equal to method.By using thes we can duplicate the vector and remove the vecotr in java
By Devendra on Nov 11, 2010
Well on older Java you can do this if it is a String, or you’d have to have the equals overloaded on the object in the Vector.
Vector newVec = new Vector();
newVec.add(“1″);
newVec.add(“2″);
newVec.add(“1″);
newVec.add(“2″);
newVec.add(“1″);
System.out.println(newVec.toString());
for(int i=0; i<newVec.size(); i++)
{
int cP = newVec.lastIndexOf(newVec.get(i));
if(cP != i)
{
newVec.remove(cP);
i-;
}
}
System.out.println(newVec.toString());
By Jay on Mar 10, 2011
Very Good….Keep up the good work..
By Lakshay on Dec 24, 2012