Tuesday, August 22, 2006

Collection Examples

I am drilling on using collections, specifically the "Set" collection.

Here is an example using a simple Set collection:

import java.util.*;

public class FindDups2 {
public static void main(String[] args) {
Set uniques = new HashSet();
Set dups = new HashSet();

for (String a : args)
if (!uniques.add(a))
dups.add(a);

// Destructive set-difference
uniques.removeAll(dups);

System.out.println("Unique words: " + uniques);
System.out.println("Duplicate words: " + dups);
}
}
The program is called with "java findDups2 (here you would pass the arguments)" The above will return you a list of the Unique words and the duplicate words passed in its arguments.

Based on the above, objects could also be checked for duplicates, or specific members of objects such as id numbers, names, addresses, etc.

Taking mental note of this for future operations...

No comments: