Saturday March 08, 2003
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 in Java
at Mar 08 2003, 07:15:42 AM MST
5 Comments
Search This Site
Recent Entries
- Secure JSON Services with Play Scala and SecureSocial
- My What's New in Spring 3.1 Presentation
- Twitter's Open Source Summit: Bootstrap 2.0 Edition
- Refreshing AppFuse's UI with Twitter Bootstrap
- 2011 - A Year in Review
- Upgrading AppFuse to Spring Security 3.1 and Spring 3.1
- What have I been working on at Taleo?
- Our Engaging Trip to Paris and Antwerp
- My HTML5 with Play Scala, CoffeeScript and Jade Presentation from Devoxx 2011
- Deploying Java and Play Framework Apps to the Cloud with James Ward
Posted by Lance on March 08, 2003 at 10:23 AM 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 10:55 AM 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 08, 2003 at 09:16 PM MST #
Posted by Anonymous on March 08, 2003 at 11:03 PM 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 10:28 AM MST #