get Intersection between two Set - Java java.util

Java examples for java.util:Set Intersection

Description

get Intersection between two Set

Demo Code


//package com.java2s;
import java.util.HashSet;
import java.util.Set;

public class Main {
    public static <T> Set<T> getIntersection(Set<T>... collections) {
        Set<T> sets = new HashSet<>();
        if (collections.length < 2)
            return sets;
        sets = collections[0];/*from  ww  w.  j  ava 2  s  .c om*/
        for (int i = 1; i < collections.length; i++) {
            Set<T> c = sets;
            Set<T> c2 = collections[i];
            sets.clear();
            for (T it : c) {
                if (c2.contains(it)) {
                    sets.add(it);
                }
            }
        }
        return sets;
    }
}

Related Tutorials