get Intersection between two HashSet - Java Collection Framework

Java examples for Collection Framework:HashSet

Description

get Intersection between two HashSet

Demo Code


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

public class Main {
    public static <T> HashSet<T> getIntersection(HashSet<T> set1,
            HashSet<T> set2) {
        HashSet<T> set = new HashSet<T>();

        for (T elem : set1)
            if (set2.contains(elem))
                set.add(elem);/*from  w  ww  . j a v  a 2 s . c o m*/
        return set;
    }

    public static <T, F> HashMap<T, F> getIntersection(HashMap<T, F> map1,
            HashMap<T, F> map2) {
        HashMap<T, F> map = new HashMap<T, F>();

        for (T elem : map1.keySet())
            if (map2.containsKey(elem)
                    && map2.get(elem).equals(map1.get(elem)))
                map.put(elem, map1.get(elem));
        return map;
    }
}

Related Tutorials