How to convert String[] (Array) to Collection, like ArrayList or HashSet?
Asked
Active
Viewed 1.8e+01k times
75
-
1Isn't there something like `java.util.Arrays.asList(array)` ? – Less Aug 16 '12 at 12:00
9 Answers
148
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));
Mohan
- 5,630
- 6
- 25
- 33
-
1
-
@StéphaneMillien caution: this thows an `IllegalArgumentException` if duplicate values are present – Reimeus Apr 18 '21 at 10:58
9
Collections.addAll provides the shortest (one-line) receipt
Having
String[] array = {"foo", "bar", "baz"};
Set<String> set = new HashSet<>();
You can do as below
Collections.addAll(set, array);
dax-nb
- 99
- 1
- 2
3
If you really want to use a set:
String[] strArray = {"foo", "foo", "bar"};
Set<String> mySet = new HashSet<String>(Arrays.asList(strArray));
System.out.println(mySet);
output:
[foo, bar]
Reimeus
- 152,723
- 12
- 195
- 261
2
It's a old code, anyway, try it:
import java.util.Arrays;
import java.util.List;
import java.util.ArrayList;
public class StringArrayTest
{
public static void main(String[] args)
{
String[] words = {"word1", "word2", "word3", "word4", "word5"};
List<String> wordList = Arrays.asList(words);
for (String e : wordList)
{
System.out.println(e);
}
}
}
Adelmo Pereira
- 33
- 4
2
Whilst this isn't strictly an answer to this question I think it's useful.
Arrays and Collections can bother be converted to Iterable which can avoid the need for performing a hard conversion.
For instance I wrote this to join lists/arrays of stuff into a string with a seperator
public static <T> String join(Iterable<T> collection, String delimiter) {
Iterator<T> iterator = collection.iterator();
if (!iterator.hasNext())
return "";
StringBuilder builder = new StringBuilder();
T thisVal = iterator.next();
builder.append(thisVal == null? "": thisVal.toString());
while (iterator.hasNext()) {
thisVal = iterator.next();
builder.append(delimiter);
builder.append(thisVal == null? "": thisVal.toString());
}
return builder.toString();
}
Using iterable means you can either feed in an ArrayList or similar aswell as using it with a String...
parameter without having to convert either.
JonnyRaa
- 6,268
- 5
- 39
- 43
0
String[] w = {"a", "b", "c", "d", "e"};
List<String> wL = Arrays.asList(w);
user207421
- 289,834
- 37
- 266
- 440
gks
- 3,368
- 3
- 27
- 44