tags:

views:

180

answers:

4

I have a java.util.Set<City> cities and I need to add cities to this set in 2 ways:

  • By adding individual city (with the help of cities.add(city) method call)

  • By adding another set of cities to this set (with the help of cities.addAll(anotherCitiesSet) method call)

But the problem in second approach is that i don't know whether there were any duplicate cities in the anotherCitiesSet.

I want to do some processing whenever a duplicate entry is tried to be entered in thecities set.

+2  A: 

Derive a class from java.util.Set, override addAll if possible (if not, create new method) and there add items one by one, and do your custom processing if you detect a duplicate entry.

Axarydax
+5  A: 

Copy the cities set (to say, citiesCopy), and then call citiesCopy.retainAll(anotherCitiesSet) - the resulting set in citiesCopy will contain the intersection of the two sets, thus allowing you to easily see which cities are duplicated, if any.

Alternatively, loop through the second set and manually add each of the elements, checking the return value from add() each time:

for(java.util.Set<City> c : anotherCitiesSet) {
    if(cities.add(c)) {
        // c was a duplicate, do something?
    }
}
Amber
+1  A: 

You will need to check for duplicates before you call addAll:

Set<City> cities = getCities();
Set<City> otherCities = getOtherSetOfCities();
Set<City> duplicates = new HashSet<City>(otherCities);
duplicates.retainAll(cities);
// now duplicates contains all City objects that are in otherCities and cities
Joachim Sauer
A: 

Before your cities.addAll() do:

Set<City> intersection = new HashSet<City>(cities);
cities.retainAll(anotherCitiesSet);

// Process all the items in the intersection, these are your duplicates
...

cities.addAll(anotherCitiesSet);
Dean Povey