The problem is in the java.util.Set.addAll () method

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

  • Adding a separate city (using a method call cities.add(city))

  • By adding another set of cities to this set (using a method call cities.addAll(anotherCitiesSet))

But the problem in the second approach is that I do not know if there were any duplicated cities in anotherCitiesSet.

I want to do some processing whenever a duplicate record tries to be entered into a set cities.

+5
source share
5 answers

cities (, citiesCopy), citiesCopy.retainAll(anotherCitiesSet) - citiesCopy , , , .

, , add():

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

java.util.Set, addAll, ( , ) , .

+2

, 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
+1

, cities.addAll():

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

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

cities.addAll(anotherCitiesSet);
0

I believe that the most elegant solution is to use an implementation java.util.Set, for example java.util.HashSet. For example, the following code adds all the integers in the set dto set c, where duplicates are not added .

The code:

import java.util.HashSet;
import java.util.LinkedList;

import com.google.common.base.Joiner;

public class CollectionsTest {

    public static void main(String[] args) {
        HashSet<Integer> c = new HashSet<>();
        c.add(0);
        c.add(1);
        c.add(2);

        HashSet<Integer> d = new HashSet<>();
        d.add(2);
        d.add(3);

        System.out.println("c = " + Joiner.on(", ").join(c));
        System.out.println("d = " + Joiner.on(", ").join(d));
        c.addAll(d);
        System.out.println("c.addAll(d) = " + Joiner.on(", ").join(c));

    }

}

Output:

c = 0, 1, 2
d = 2, 3
c.addAll(d) = 0, 1, 2, 3

To work HashSetcorrectly for objects of City objection City, methods hashCode()and must be redefined equals(). Then HashSetremove duplicates when used addAll()for free!

0
source

All Articles