Create Set from Collection and Array - Java java.util

Java examples for java.util:Collection to Array

Description

Create Set from Collection and Array

Demo Code


//package com.java2s;

import java.util.Collection;
import java.util.Collections;

import java.util.HashSet;

import java.util.Set;

public class Main {
    public static void main(String[] argv) {
        Collection xs = java.util.Arrays.asList("asdf", "java2s.com");
        System.out.println(makeSet(xs));
    }//from   w w w  .  j  av  a2  s  .  com

    public static <A> Set<A> makeSet(Collection<A> xs) {
        if (xs.size() == 0)
            return Collections.<A> emptySet();
        else if (xs.size() == 1)
            return Collections.singleton(xs.iterator().next());
        else {
            Set<A> set = new HashSet<A>(xs.size());
            set.addAll(xs);
            return set;
        }
    }

    @SafeVarargs
    public static <A> Set<A> makeSet(A... xs) {
        if (xs.length == 0)
            return Collections.<A> emptySet();
        else if (xs.length == 1)
            return Collections.singleton(xs[0]);
        else {
            Set<A> set = new HashSet<A>(xs.length);
            Collections.addAll(set, xs);
            return set;
        }
    }
}

Related Tutorials