20030308 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

Comments:

Why not use a Set instead? Sets only allow one instance of an object.

Posted by Lance on March 08, 2003 at 09: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 09:55 AM MST #

There is always contains. prop.add(someString); ..... 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 08:16 PM MST #

What about HashSet?

Posted by Anonymous on March 08, 2003 at 10: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: List result = (List) new ArrayList(mySet); If you need the items to be ordered use TreeSet, else choose HashSet. HTH Fokko

Posted by Anonymous on March 09, 2003 at 09:28 AM MST #

Post a Comment:
  • HTML Syntax: Allowed
Click me to subscribe
Matt Raible is a Web Architect who enjoys developing applications with open source technologies. Contact me for rates.
« January 2009
SunMonTueWedThuFriSat
    
1
2
3
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
       
Today

Recent Entries

Tag Cloud