lonesome lonesome - 5 months ago 14
Java Question

How to calculate intersection between more than two Hashsets?

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);

}


Considering the above code and the fact that the 4
HashSet
s are populated elsewhere, My aim is to contain all element(s) that are common in all 4. My question is that first of all, if I am doing it right and secondly, if there is a better (in case i am doing it right) way to do it or (in case i am wrong) a solution for this situation?

Answer

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;
}
Comments