Returns the intersection of two sets. - Java java.util

Java examples for java.util:Set Intersection

Description

Returns the intersection of two sets.

Demo Code


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

public class Main {
    /**/*from  w w  w .  j  a  va 2s.c  o  m*/
     * Returns the intersection of two sets. It calls {@link Set#retainAll(java.util.Collection)} but returns a new set
     * containing the elements of the intersection.
     * 
     * @param set1
     *            the first set
     * @param set2
     *            the second set
     * @return the intersection of the sets
     */
    public static <V> Set<V> intersection(Set<V> set1, Set<V> set2) {
        Set<V> intersection = new HashSet<V>();
        intersection.addAll(set1);
        intersection.retainAll(set2);
        return intersection;
    }
}

Related Tutorials