Java Set Intersect intersection(Set first, Set second)

Here you can find the source of intersection(Set first, Set second)

Description

Return a new Set with elements that are in the first and second passed collection.

License

Open Source License

Parameter

Parameter Description
T Type of set
first First set
second Second set

Return

a new set (depending on input type) with elements in first and second

Declaration

static <T> Set<T> intersection(Set<T> first, Set<T> second) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

public class Main {
    /**//  w w  w . j a v a 2s .com
     * Return a new Set with elements that are in the first and second passed collection.
     * If one set is null, an empty Set will be returned.
     * @param  <T>    Type of set
     * @param  first  First set
     * @param  second Second set
     *
     * @return a new set (depending on input type) with elements in first and second
     */
    static <T> Set<T> intersection(Set<T> first, Set<T> second) {
        Set<T> result = new HashSet<T>();
        if ((first != null) && (second != null)) {
            result.addAll(first);
            //            result.retainAll(second);
            Iterator<T> iter = result.iterator();
            boolean found;
            while (iter.hasNext()) {
                T item = iter.next();
                found = false;
                for (T s : second) {
                    if (s.equals(item))
                        found = true;
                }
                if (!found)
                    iter.remove();
            }
        }

        return result;
    }
}

Related

  1. intersect(Set a, Set b)
  2. intersectComparable(Set left, Set right)
  3. intersection(final Set set1, final Set set2)
  4. intersection(Set a, Set b)
  5. intersection(Set sa, Set sb)
  6. intersection(Set s1, Set s2)
  7. intersection(Set setA, Set setB)
  8. intersection(Set setA, Set setB)
  9. intersectionP(Set s1, Set s2)