Java Collection Union union(Collection> sets)

Here you can find the source of union(Collection> sets)

Description

Determines the union of a collection of sets.

License

Open Source License

Parameter

Parameter Description
T a parameter
sets Basic collection of sets.

Return

The set of distinct elements of all given sets.

Declaration

public static <T> Set<T> union(Collection<Set<T>> sets) 

Method Source Code


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

import java.util.ArrayList;

import java.util.Collection;

import java.util.HashSet;
import java.util.Iterator;
import java.util.List;

import java.util.Set;

public class Main {
    /**//www .  j  a v  a2  s  . com
     * Determines the union of a collection of sets.
     * 
     * @param <T>
     * @param sets
     *            Basic collection of sets.
     * @return The set of distinct elements of all given sets.
     */
    public static <T> Set<T> union(Collection<Set<T>> sets) {
        Set<T> result = new HashSet<>();
        if (sets.isEmpty()) {
            return result;
        }
        Iterator<Set<T>> iter = sets.iterator();
        result.addAll(iter.next());

        if (sets.size() == 1) {
            return result;
        }

        while (iter.hasNext()) {
            result.addAll(iter.next());
        }
        return result;
    }

    public static <T> Set<T> union(Set<T>... sets) {
        List<Set<T>> list = new ArrayList<>(sets.length);
        for (Set<T> set : sets) {
            list.add(set);
        }
        return union(list);
    }
}

Related

  1. union(Collection c1, Collection c2)
  2. union(Collection coll)
  3. union(Collection collection1, Collection collection2)
  4. union(Collection c1, Collection c2)
  5. union(Collection a, Collection b)
  6. union(Collection c1, Collection c2)
  7. union(Collection initial, Collection other)
  8. union(Collection lhs, Collection rhs)