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?
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:
Any ideas? |
|||||||||||||||||
|
Like this:
|
|||||||||||||||||||||
|
That's Collections.addAll(java.util.Collection, T...) from jdk1.6. |
|||||||||||||||||||||
|
With Guava you can do:
|
|||||||||||||||||
|
After you do Here is a sample method, you can write:
|
|||||||||||||||||||||
|
Quickly : you can do :
and to reverse
|
|||||
|
In GS Collections, the following will work:
Note: I am a developer on GS Collections |
|||
|
Sometime using some standard libraries helps a lot. Try to look at the Apache Commons Collections. In this case your problems is simply transformed to something like this
And here is the CollectionsUtils javadoc |
|||||||||
|
But I think this would be more efficient:
|
|||