Initializing a Set with an Iterable

VaidAbhishek picture VaidAbhishek · May 8, 2013 · Viewed 27.7k times · Source

I want to initialize a Set Implementation (HashSet) in Java with an Iterable. However, the constructor of HashSet doesn't accept Iterables, but only Collections type objects.

Is there a way to convert from Iterable to some subtype of Collections.

Answer

ConnorWGarvey picture ConnorWGarvey · May 8, 2013

You can use Guava.

Set<T> set = Sets.newHashSet(iterable);

or to make it read like a sentence static import,

import static com.google.common.collect.Sets.*;

Set<T> set = newHashSet(iterable);