Java Set Intersect intersect(final Set firstSet, final Set secondSet)

Here you can find the source of intersect(final Set firstSet, final Set secondSet)

Description

Utility method returning the intersection between the given sets (i.e.

License

Apache License

Parameter

Parameter Description
firstSet The first set.
secondSet The second set.

Return

The intersection between the given sets (i.e. elements present among both sets).
Never returns null ; if no intersection, returns empty set.

Declaration

public static <T> Set<T> intersect(final Set<T> firstSet, final Set<T> secondSet) 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.util.*;

public class Main {
    /**/* w  ww  . j  av a  2s  .c o  m*/
     * Utility method returning the intersection between the given sets (i.e. elements present among both sets).
     *
     * @param firstSet
     *         The first set.
     * @param secondSet
     *         The second set.
     * @return The intersection between the given sets (i.e. elements present among both sets).<br/>
     * Never returns {@code null} ; if no intersection, returns empty set.
     */
    public static <T> Set<T> intersect(final Set<T> firstSet, final Set<T> secondSet) {

        if (isEmpty(firstSet)) {
            return secondSet == null ? new HashSet<T>(0) : secondSet;
        }
        if (isEmpty(secondSet)) {
            return firstSet;
        }

        firstSet.retainAll(secondSet);

        return firstSet;
    }

    /**
     * Returns if the given {@code collection} is {@code null} or empty.
     *
     * @param collection
     *         The collection to test.
     * @return {@code true} if the given {@code collection} is {@code null} or {@code empty}.
     */
    public static <C extends Collection<?>> boolean isEmpty(C collection) {
        return collection == null || collection.isEmpty();
    }

    /**
     * Returns if the given {@code array} is {@code null} or empty.
     *
     * @param array
     *         The array to test.
     * @return {@code true} if the given {@code array} is {@code null} or {@code empty}.
     */
    public static <T extends Object> boolean isEmpty(T[] array) {
        return array == null || array.length == 0;
    }

    /**
     * Returns if the given {@code map} is {@code null} or empty.
     *
     * @param map
     *         The map to test.
     * @return {@code true} if the given {@code map} is {@code null} or {@code empty}.
     */
    public static <M extends Map<?, ?>> boolean isEmpty(M map) {
        return map == null || map.isEmpty();
    }
}

Related

  1. getIntersection(Set a, Set b)
  2. getIntersection(Set s1, Set s2)
  3. intersect(Collection set1, Collection set2)
  4. intersect(Set one, Set two)
  5. intersect(Set set1, Set set2)
  6. intersect(Set a, Set b)
  7. intersect(Set a, Set b)