Convert Iterable as Set - Java Collection Framework

Java examples for Collection Framework:Iterable

Description

Convert Iterable as Set

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 <T> Set<T> asSet(final Iterable<? extends T> iterable) {
        return (iterable instanceof Collection) ? new HashSet<T>(
                (Collection<? extends T>) iterable) : new HashSet<T>() {
            private static final long serialVersionUID = 3109256773218160485L;
            {//from  w w w . j a  v  a2  s . co m
                if (iterable != null) {
                    for (final T t : iterable) {
                        add(t);
                    }
                }
            }
        };
    }

    public static <T> Set<T> asSet(final T t, final T... ts) {
        final Set<T> set = new HashSet<T>(ts.length + 1);
        set.add(t);
        Collections.addAll(set, ts);
        return set;
    }
}

Related Tutorials