- We have to create a list of String.
- Then pass that string top Hashset.(i.e)HashSet will not allow duplicates.
- So the resultant list is a unique list.
- The same procedure you have to follow for Interger etc.For user definied list we have to override
- hashCode and Equals method.That you can see in my next post.
- package com.utilitySample;
- import org.apache.commons.lang.StringUtils;
- public class RemoveDuplicate {
- public static void main(String[] args) {
- List<String> arrayList1 = new ArrayList<String>();
- arrayList1.add("vel");
- arrayList1.add("vel");
- arrayList1.add("dinesh");
- arrayList1.add("dinesh");
- arrayList1.add("dinesh");
- arrayList1.add("prasanth");
- List<String> arrayList2 = new ArrayList<String>(new HashSet<String>(arrayList1));
- for (String item : arrayList2){
- System.out.println(item);
- }
- }
- }
Output :
dinesh
vel
prasanth
vel
prasanth
Replace the line 14 with the below code
ReplyDeletearrayList1 = new ArrayList(new HashSet(arrayList1));
What if i am storing an user defined object in the list? How will you remove the duplicate objects from the list?
ReplyDeleteA quick reply would be appreciated.
see this post http://thecodemechanic.blogspot.in/2013/07/remove-duplicate-in-userdefinied-list.html
Delete