Search code examples
javaintersectionhashsetretain

How do I calculate intersection between more than two HashSets?


Considering the code below and the fact that the 4 HashSets are populated elsewhere.

My aim is to contain all element(s) that are common in all 4 HashSets.

My question is that first of all, am I doing it right? Secondly, if I'm doing it right, is there a better way to do it? If not, then what solution do I have for this problem?

static Set<String> one=new HashSet<>();
static Set<String> two=new HashSet<>();
static Set<String> three=new HashSet<>();
static Set<String> four=new HashSet<>();

private static void createIntersectionQrels() {
    ArrayList<String> temp = new ArrayList<>();
    Set<String> interQrels = new HashSet<>();

    temp.addAll(one);
    one.retainAll(two);
    interQrels.addAll(one);
    one.addAll(temp);
    one.retainAll(three);
    interQrels.addAll(one);
    one.addAll(temp);
    one.retainAll(four);
    interQrels.addAll(one);
    one.addAll(temp);

    interQrels.retainAll(two);
    interQrels.retainAll(three);
    interQrels.retainAll(four);
}

Solution

  • I think you can simply can call retainAll() on the first set, using the second, third, and fourth sets as parameters:

    private static Set<String> getIntersectionSet() {
        // create a deep copy of one (in case you don't wish to modify it)
        Set<String> interQrels = new HashSet<>(one);
    
        interQrels.retainAll(two);     // intersection with two (and one)
        interQrels.retainAll(three);   // intersection with three (and two, one)
        interQrels.retainAll(four);    // intersection four (and three, two, one)
    
        return interQrels;
    }