The Set Interface




Two general purpose Set implementations in the JDK:




Example: Let c be a collection. Create another collection that contains the same elements, but which does not contain duplicate elements.

Collection<Integer> c = new ArrayList<Integer>();
// assume elements have been added to c
Collection<Integer> noDups = new HashSet<Integer>(c);



Exercise:
Write a program that takes words on the command line and prints out any duplicate words, the number of distinct words, and a list of the words without duplicates.




Note: A HashSet doesn't guarantee any sort of ordering on the elements in a set. Use a TreeSet in the previous example if you want to words in the set printed in alphabetical order.


Exercise: Write a program that takes words on the command line and prints the words that occur only once, and then prints the words that occur more than once.

Sample Run:
java RemoveDuplicates hello world hello again
unique words: [world, again]
duplicated words: [hello]