package com.michaelthomas.set.hashset; /** * @author Michael Thomas (www.michael-thomas.com) michael@michael-thomas.com * */ import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; /** * @author Michael Thomas (www.michael-thomas.com) michael@michael-thomas.com * */ public class MyHashSet { //NOTE: For learning, you must see the JUnit test file in the /test/ directory and matching package! Set buildHashSetCarVendors1() { Set set = new HashSet(); set.add("BMW"); set.add("Ford"); set.add("Toyota"); return set; } Set buildHashSetCarVendors2() { Set set = new HashSet(); set.add("BMW"); set.add("Mercedes"); set.add("Chevorlet"); return set; } Set buildHashSetWithNulls() { Set set = new HashSet(); set.add("BMW"); set.add(null); return set; } List buildListDuplicateCarVendors() { List list = new ArrayList(); list.add("BMW"); list.add("Ford"); list.add("Toyota"); list.add("Toyota"); return list; } List buildListDuplicateCarVendors2() { List list = new ArrayList(); list.add("BMW"); return list; } List removeDupsFromAList( List dupsList) { Set unique = new HashSet(dupsList); //Set doesn't allow dups. List uniqueList = new ArrayList(unique); //Convert from set to ArrayList. return uniqueList; } Set returnDups( Set set1, Set set2) { Set dups = new HashSet(); Set uniqueSet = new HashSet(set1); for (Iterator iterator = set2.iterator(); iterator.hasNext();) { String string = (String) iterator.next(); if ( ! uniqueSet.add(string)) { //If the string will not add then it is a dup! dups.add(string); } } return dups; } List returnDups( List list1, List list2) { Set dups = new HashSet(); Set uniqueSet = new HashSet(); for (Iterator iterator = list1.iterator(); iterator.hasNext();) { String string = (String) iterator.next(); if ( ! uniqueSet.add(string)) { //If the string will not add then it is a dup! dups.add(string); } } for (Iterator iterator = list2.iterator(); iterator.hasNext();) { String string = (String) iterator.next(); if ( ! uniqueSet.add(string)) { //If the string will not add then it is a dup! dups.add(string); } } List dupsList = new ArrayList(dups); return dupsList; } Set ReturnItemsInBothSets(Set set1, Set set2) { Set inBothFiles = new HashSet(set1); inBothFiles.retainAll(set2); //Keep anything that is in both files! (Dups) return inBothFiles; } Set ReturnItemsNotInBothSets(Set set1, Set set2) { //Identify items in both files. Set inBothFiles = new HashSet(set1); inBothFiles.retainAll(set2); //Keep anything that is in both files! (Dups) //Create an unique set of all items Set notInBothSets = new HashSet(set1); //Create a new set. notInBothSets.addAll(set2); //has a unique set of all items. //Now remove any items in both notInBothSets.removeAll(inBothFiles); //Remove all dups! return notInBothSets; } }