How do I remove duplicates in a List?
I have a List that may contain duplicates and I need to filter out the duplicates (so I don't get a foreign key violation when inserting records). Are there any Jakarta' Commons utilities to do this? I can see a few solutions to my problem:
- Present it on the UI. This might be tough since I'm using a select box JavaScript library. Hmmm, I am using a custom setter for the String[] that gets sent in, maybe I can do it there - checking to see if the ArrayList I'm setting already contains the given String.
- Filter it out in the business layer.
- Use a type of List that doesn't allow duplicates, and just ignores a duplicate value when you try to add it.
I just thought of #1 while writing this post. It's cool how talking about your problems can help solve them - no wonder shrinks get paid so much. I'm still interested in any proposed utility classes.


Posted by Lance on March 08, 2003 at 04:23 PM MST #
Matt,
You might try something like this in your formbean setter?
ArrayList list = new ArrayList(); list.add("CCCC"); list.add("AAAA"); list.add("BBBB"); list.add("AAAA"); list.add("CCCC"); list.add("AAAA"); Collections.sort(list); boolean[] dupSet = new boolean[list.size()]; for (int i = 0; i < list.size() - 1;) { dupSet[i] = ((String) list.get(i++)).equals(list.get(i)); } for (int i = dupSet.length -1; i >= 0; --i) { if (dupSet[i]) list.remove(i); } dupSet = null; for (int i = 0; i < list.size(); i++) { System.out.println(list.get(i).toString()); }Posted by Anonymous on March 08, 2003 at 04:55 PM MST #
There is always contains.
..... in the bean....
public void add(Object obj) { if(!this.prop.contains(obj)) this.prop.add(obj); }No need to re-implement the wheel :)
Posted by Carl Fyffe on March 09, 2003 at 03:16 AM MST #
Posted by Anonymous on March 09, 2003 at 05:03 AM MST #
Using a Set seems to be the right approach. If the output has to be a List, add the items to a Set first and then use:
If you need the items to be ordered use TreeSet, else choose HashSet.
HTH
Fokko
Posted by Anonymous on March 09, 2003 at 04:28 PM MST #