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
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
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));
}
Like this:
Set<T> mySet = new HashSet<T>(Arrays.asList<T>(someArray));
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); }
With Guava you can do:
T[] array = ...
Set<T> set = Sets.newHashSet(array);
Set<T> mySet = new HashSet<T>();
Collections.addAll(mySet, myArray);
That's Collections.addAll(java.util.Collection, T...) from jdk1.6.