这个问题已经在这里有一个答案:
- 如何将数组转换为一组Java的 17个回答
如何的String [](数组)转换为Collection,如ArrayList或HashSet的?
这个问题已经在这里有一个答案:
如何的String [](数组)转换为Collection,如ArrayList或HashSet的?
Arrays.asList()将在这里做的伎俩。
String[] words = {"ace", "boom", "crew", "dog", "eon"};
List<String> wordList = Arrays.asList(words);
对于转换设置,可以参考以下做
Set<T> mySet = new HashSet<T>(Arrays.asList(words));
最简单的方法是:
String[] myArray = ...;
List<String> strs = Arrays.asList(myArray);
使用便捷的阵列实用工具类。 请注意,你甚至可以做
List<String> strs = Arrays.asList("a", "b", "c");
Collections.addAll提供最短(单行)收据
有
String[] array = {"foo", "bar", "baz"};
Set<String> set = new HashSet<>();
您可以按照以下做
Collections.addAll(set, array);
java.util.Arrays.asList(new String[]{"a", "b"})
这是一个旧的代码,反正试试吧:
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);
}
}
}
如果你真的想用一组:
String[] strArray = {"foo", "foo", "bar"};
Set<String> mySet = new HashSet<String>(Arrays.asList(strArray));
System.out.println(mySet);
输出:
[foo, bar]
最简单的方法就是通过
Arrays.asList(stringArray);
虽然这不是严格意义上的回答这个问题,我认为这是非常有用的。
数组和集合可以麻烦被转换为可迭代能够避免用于执行硬转换的需要。
比如我写了这个加盟的东西列表/阵列成一个字符串用分隔符
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();
}
使用迭代意味着你可以在一个ArrayList或类似的藏汉饲料与一个使用它String...
参数,而无需任何转换。
String[] w = {"a", "b", "c", "d", "e"};
List<String> wL = Arrays.asList(w);