82

如何将 String[] (Array) 转换为 Collection,如 ArrayList 或 HashSet?

4

9 回答 9

161

Arrays.asList() 在这里可以解决问题。

String[] words = {"ace", "boom", "crew", "dog", "eon"};   

List<String> wordList = Arrays.asList(words);  

要转换为 Set,您可以执行以下操作

Set<T> mySet = new HashSet<T>(Arrays.asList(words)); 
于 2012-08-16T12:02:02.627 回答
11

最简单的方法是:

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

使用方便的Arrays实用程序类。请注意,您甚至可以这样做

List<String> strs = Arrays.asList("a", "b", "c");
于 2012-08-16T12:00:04.233 回答
9

Collections.addAll 提供最短(单行)收据

String[] array = {"foo", "bar", "baz"}; 
Set<String> set = new HashSet<>();

您可以执行以下操作

Collections.addAll(set, array); 
于 2014-07-03T13:31:29.400 回答
3

这是一个旧代码,无论如何,尝试一下:

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);
      }
    }
}
于 2012-08-16T12:01:43.577 回答
3

如果你真的想使用一个集合:

String[] strArray = {"foo", "foo", "bar"};  
Set<String> mySet = new HashSet<String>(Arrays.asList(strArray));
System.out.println(mySet);

输出:

[foo, bar]
于 2012-08-16T12:04:54.097 回答
3

虽然这并不是对这个问题的严格回答,但我认为它很有用。

数组和集合可以麻烦转换为 Iterable,这样可以避免执行硬转换的需要。

例如,我写这个是为了将列表/数组加入到带有分隔符的字符串中

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.

于 2014-09-11T13:29:48.193 回答
2
java.util.Arrays.asList(new String[]{"a", "b"})
于 2012-08-16T12:00:08.883 回答
1

最简单的方法是通过

Arrays.asList(stringArray);
于 2012-08-16T12:00:13.547 回答
0
String[] w = {"a", "b", "c", "d", "e"};  

List<String> wL = Arrays.asList(w);  
于 2012-08-16T12:02:57.633 回答