Java Set Union union(String[] set1, String[] set2)

Here you can find the source of union(String[] set1, String[] set2)

Description

Same as union, but for Strings.

License

Open Source License

Parameter

Parameter Description
set1 first set of Strings
set2 second set of Strings

Return

set union of set1 and set2

Declaration

public static String[] union(String[] set1, String[] set2) 

Method Source Code

//package com.java2s;
// Refer to LICENSE for terms and conditions of use.

import java.util.*;

public class Main {
    /**//from ww  w. j ava2 s . c  o  m
     * Return the set union of two array of objects.
     *
     * @param set1 first set of objects
     * @param set2 second set of objects
     * @return set union of set1 and set2
     */
    public static Object[] union(Object[] set1, Object[] set2) {
        Object[] set = new Object[set1.length + set2.length];
        System.arraycopy(set1, 0, set, 0, set1.length);
        System.arraycopy(set2, 0, set, set1.length, set2.length);
        return unique(set);
    }

    /**
     * Same as union, but for Strings.
     *
     * @param set1 first set of Strings
     * @param set2 second set of Strings
     * @return set union of set1 and set2
     */
    public static String[] union(String[] set1, String[] set2) {
        String[] set = new String[set1.length + set2.length];
        System.arraycopy(set1, 0, set, 0, set1.length);
        System.arraycopy(set2, 0, set, set1.length, set2.length);
        return (String[]) unique(set);
    }

    /**
     * Return a set (array of unique objects).
     *
     * @param elements array of objects, possibly with duplicates
     * @return array of objects with duplicates removed; order is not preserved.
     */
    public static Object[] unique(Object[] elements) {
        Hashtable h = new Hashtable();
        Object o = new Object();
        for (int i = 0; i < elements.length; i++) {
            h.put(elements[i], o);
        }
        Object[] el2 = new Object[h.size()];
        Enumeration e = h.keys();
        int i = 0;
        while (e.hasMoreElements()) {
            el2[i++] = e.nextElement();
        }
        return el2;
    }

    /**
     * Same as unique, but for Strings.
     *
     * @param elements array of Strings, possibly with duplicates
     * @return array of Strings with duplicates removed; order is not preserved.
     */
    public static String[] unique(String[] elements) {
        Hashtable h = new Hashtable();
        Object o = new Object();
        for (int i = 0; i < elements.length; i++) {
            h.put(elements[i], o);
        }
        String[] el2 = new String[h.size()];
        Enumeration e = h.keys();
        int i = 0;
        while (e.hasMoreElements()) {
            el2[i++] = (String) e.nextElement();
        }
        return el2;
    }
}

Related

  1. union(Set a, Set b)
  2. union(Set left, Set right)
  3. union(Set setA, Set setB)
  4. union(Set setA, Set setB)
  5. union(Set... sets)