Returns union of two collections. - Java java.util

Java examples for java.util:Collection Union

Description

Returns union of two collections.

Demo Code


//package com.java2s;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

public class Main {
    public static void main(String[] argv) {
        Collection coll1 = java.util.Arrays.asList("asdf", "java2s.com");
        Collection coll2 = java.util.Arrays.asList("asdf", "java2s.com");
        System.out.println(union(coll1, coll2));
    }// w w  w .  jav a2  s  .  com

    /**
     * Returns union of two collections.
     *
     * @param <T> the generic type
     * @param coll1 the coll1
     * @param coll2 the coll2
     * @return the collection
     */
    public static <T> Collection<T> union(Collection<T> coll1,
            Collection<T> coll2) {
        Set<T> union = new HashSet<T>(coll1);
        union.addAll(new HashSet<T>(coll2));

        return union;
    }
}

Related Tutorials