Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: How to convert String[] to List or Set [duplicate]

How to convert String[] (Array) to Collection, like ArrayList or HashSet?

like image 815
Mark Avatar asked Aug 16 '12 11:08

Mark


People also ask

Can we convert string [] to string?

So how to convert String array to String in java. We can use Arrays. toString method that invoke the toString() method on individual elements and use StringBuilder to create String. We can also create our own method to convert String array to String if we have some specific format requirements.

Can we convert Set to list in Java?

We can simply convert a Set into a List using the constructor of an ArrayList or LinkedList.


2 Answers

Arrays.asList() would do the trick here.

String[] words = {"ace", "boom", "crew", "dog", "eon"};     List<String> wordList = Arrays.asList(words);   

For converting to Set, you can do as below

Set<T> mySet = new HashSet<T>(Arrays.asList(words));  
like image 115
Mohan Avatar answered Oct 02 '22 18:10

Mohan


The easiest way would be:

String[] myArray = ...; List<String> strs = Arrays.asList(myArray); 

using the handy Arrays utility class. Note, that you can even do

List<String> strs = Arrays.asList("a", "b", "c"); 
like image 35
Dirk Avatar answered Oct 02 '22 19:10

Dirk