Reputation: 21200
In Java, what's the qucikest way to convert an array to a List or a set?
String[] a = {"Test1", "test2"};
List<String> l = new ArrayList<String>();
Upvotes: 1
Views: 316
Reputation: 8225
Arrays.asList() works for your example of String[], but if your're converting a primitive array, such as int[] or double[], then this will produce a single item list of the array. A good solution is to use Google Guava's primitive helper classes, such as Ints:
int[] a = new int[]{1,2,3};
List<Integer> l = Ints.asList(a);
For a more detailed explanation, see this answer.
Upvotes: 0
Reputation: 1944
Use Google's Guava APIs, using collections is so much simpler.
String[] a = {"Test1", "test2"};
List<String> l = Lists.newArrayList(a);
Upvotes: 0
Reputation: 62573
Use the java.util.Arrays
class.
List<String> list = Arrays.asList(new String[] {"a", "b"});
Note that the implementation of List
you get by the above method isn't the same as java.util.ArrayList
. If you want ArrayList
implementation, use
List<String> list = new ArrayList<String>(Arrays.asList(new String[] {"a", "b"}));
Upvotes: 11
Reputation: 4855
List list = Arrays.asList(array);
Collections.addAll(list, array);
One of the first google link : http://javarevisited.blogspot.com/2011/06/converting-array-to-arraylist-in-java.html
Upvotes: 0
Reputation: 3025
http://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#asList(T...)
It would depend on your definition of "quickest", but in both cases this would be it.
Upvotes: 0
Reputation: 274532
To convert an array to a list use Arrays.asList:
String[] a = {"Test1", "test2"};
List<String> list = Arrays.asList(a);
To convert an array to a set:
Set<String> set = new HashSet<String>(Arrays.asList(a));
Upvotes: 2
Reputation: 14053
From the Arrays class (doc):
List<String> l = Arrays.asList(a);
Upvotes: 1