views:

170

answers:

5

Hey,

I'd like to convert an array to a set in Java. There are some obvious ways of doing this (i.e. with a loop) but I would like something a bit neater, something like:

java.util.Arrays.asList(Object[] a);

Any ideas?

Cheers,

Pete

+5  A: 

After you do Arrays.List(array) you can execute Set set = new HashSet(list);

Here is a sample method, you can write:

public <T> Set<T> GetSetFromArray(T[] array) {
    return new HashSet<T>(Arrays.asList(array));
}
Petar Minchev
I was hoping for a method that returns a set directly from an array, does one exist?
Peter
Honestly, I doubt:)
Petar Minchev
You can write your own, if you are so eager:)
Petar Minchev
+12  A: 

Like this:

Set<T> mySet = new HashSet<T>(Arrays.asList<T>(someArray));
SLaks
+1 for generics.
JavadocMD
A: 

new HashSet<Object>(Arrays.asList(Object[] a));

But I think this would be more efficient:

final Set s = new HashSet<Object>();
for (Object o : a) { s.add(o); }
Ben S
That wouldn't really be more efficient (at least not worth thinking about).
ColinD
With the constructor version, the initial capacity of the `HashSet` is set based on the size of the array, for instance.
ColinD
A: 

With Guava you can do:

T[] array = ...
Set<T> set = Sets.newHashSet(array);
ColinD
also ImmutableSet.copyOf(array). (I like to point out also's, I guess.)
Kevin Bourrillion
+3  A: 
Set<T> mySet = new HashSet<T>();
Collections.addAll(mySet, myArray);

That's Collections.addAll(java.util.Collection, T...) from jdk1.6.

JavadocMD
You can do that with `java.util.Collections.addAll`. Plus, I wouldn't recommend Commons Collections anymore, what with it not being generified and Guava existing .
ColinD
Yeah I noticed that and altered the above before I read your comment. :)
JavadocMD