Java Collection Union union(final Collection... sets)

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

Description

iterator over all elements contained in the union of the given sets

License

Open Source License

Parameter

Parameter Description
sets a parameter

Return

intersection

Declaration

public static Iterable union(final Collection... sets) 

Method Source Code


//package com.java2s;
/*/*ww w .  java 2  s. c  o  m*/
 * SetUtils.java Copyright (C) 2019. Daniel H. Huson
 *
 *  (Some files contain contributions from other authors, who are then mentioned separately.)
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

import java.util.Collection;
import java.util.Iterator;

public class Main {
    /**
     * iterator over all elements contained in the union of the given sets
     *
     * @param sets
     * @return intersection
     */
    public static Iterable union(final Collection... sets) {
        return () -> new Iterator() {
            int which = 0;
            Iterator it = null;

            {
                while (which < sets.length && !it.hasNext()) {
                    it = sets[which++].iterator();

                }
            }

            @Override
            public boolean hasNext() {
                return which < sets.length;
            }

            @Override
            public Object next() {
                final Object result = it.next();
                while (which < sets.length && !it.hasNext()) {
                    it = sets[which++].iterator();
                }
                return result;
            }
        };
    }

    /**
     * union of two sets
     *
     * @param a
     * @param b
     * @param <T>
     * @return union
     */
    public static <T> Iterable<T> union(Collection<T> a, Collection<T> b) {
        return (Iterable<T>) union(new Collection[] { a, b });
    }
}

Related

  1. union(Collection initial, Collection other)
  2. union(Collection lhs, Collection rhs)
  3. union(Collection set1, Collection set2)
  4. union(final Collection a, final Collection b)
  5. union(final Collection c1, final Collection c2)
  6. union(final Collection a, final Collection b)
  7. unionAll(final Collection collector, final T[] a, final T[] b)