Java – how to calculate the intersection between two or more hashsets?

Consider the following code and the fact that four hashsets are populated elsewhere

My goal is to include all the elements common in all four hashsets

My question is, first of all, am I right? Secondly, if I do it right, is there a better way? If not, what is my solution to 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 call retainall() on the first group, using the second, third and fourth groups 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;
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>