Java Set Union union(Set setA, Set setB)

Here you can find the source of union(Set setA, Set setB)

Description

Union.

License

Apache License

Parameter

Parameter Description
T the generic type
setA the set a
setB the set b

Return

the sets the

Declaration

public static <T> Set<T> union(Set<T> setA, Set<T> setB) 

Method Source Code

//package com.java2s;
/*//from   w w  w . j  av  a  2s .c  om
Copyright 2014 Array-Utilities
    
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
    
http://www.apache.org/licenses/LICENSE-2.0
    
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
    
 * */

import java.util.Collection;
import java.util.Collections;

import java.util.Iterator;
import java.util.LinkedHashSet;

import java.util.Set;

public class Main {
    /**
     * Union.
     *
     * @param <T> the generic type
     * @param setA            the set a
     * @param setB            the set b
     * @return the sets the
     */
    public static <T> Set<T> union(Set<T> setA, Set<T> setB) {

        // SetA empty & SetB has values
        if (isEmpty(setA) && !isEmpty(setB)) {
            return Collections.unmodifiableSet(setB);
        }

        // SetA has values & SetB is empty
        if (!isEmpty(setA) && isEmpty(setB)) {
            return Collections.unmodifiableSet(setA);
        }

        // Both set are empty
        if (isEmpty(setA) && isEmpty(setB)) {
            return new LinkedHashSet<T>();
        }

        if (setA.equals(setB)) {
            return setA;
        }

        Set<T> setC = new LinkedHashSet<T>();
        Iterator<T> iterA = setA.iterator();
        Iterator<T> iterB = setB.iterator();

        while (iterA.hasNext()) {
            setC.add(iterA.next());
        }
        while (iterB.hasNext()) {
            setC.add(iterB.next());
        }
        return Collections.unmodifiableSet(setC);
    }

    /**
     * Checks if is empty.
     *
     * @param <E>
     *            the element type
     * @param collection
     *            the collection
     * @return true, if is empty
     */
    public static <E> boolean isEmpty(Collection<? super E> collection) {

        if ((collection.size() == 0) || (collection == null))
            return true;
        return false;
    }
}

Related

  1. union(final Set set1, final Set set2)
  2. union(final Set... elements)
  3. union(Set one, Set two)
  4. union(Set a, Set b)
  5. union(Set left, Set right)
  6. union(Set setA, Set setB)
  7. union(Set... sets)
  8. union(String[] set1, String[] set2)