Java Set Union union(Set a, Set b)

Here you can find the source of union(Set a, Set b)

Description

Returns union of a and b as a Hashtable containing all elements in a and b

License

Open Source License

Parameter

Parameter Description
a <CODE>java.util.Hashtable</CODE> to be examined
b <CODE>java.util.Hashtable</CODE> to be examined

Return

Hashtable representing union of a and b

Declaration

public static Set<?> union(Set<?> a, Set<?> b) 

Method Source Code


//package com.java2s;
/*// w  w w . j a  va  2s .c  om
 * 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.Collections;
import java.util.Set;
import java.util.HashSet;

public class Main {
    /**
     * Returns union of <CODE>a</CODE> and <CODE>b</CODE> as a
     * <CODE>Hashtable</CODE> containing all elements in <CODE>a</CODE> and <CODE>b</CODE>
     *
     * @param a <CODE>java.util.Hashtable</CODE> to be examined
     * @param b <CODE>java.util.Hashtable</CODE> to be examined
     *
     * @return <CODE>Hashtable</CODE> representing union
     * of <CODE>a</CODE> and <CODE>b</CODE>
     */
    public static Set<?> union(Set<?> a, Set<?> b) {
        if (a == null || b == null || a.size() == 0 || b.size() == 0)
            return Collections.EMPTY_SET;

        Set<Object> union = new HashSet<Object>((a.size() < b.size()) ? b : a);
        Set<?> src = (a.size() < b.size()) ? b : a;

        for (Object o : src) {
            if (!union.contains(o))
                union.add(o);
        }
        return union;
    }
}

Related

  1. union(final Iterable> elements)
  2. union(final Set set1, final Set set2)
  3. union(final Set... elements)
  4. union(Set one, Set two)
  5. union(Set left, Set right)
  6. union(Set setA, Set setB)
  7. union(Set setA, Set setB)
  8. union(Set... sets)