如何将String []转换为集合?

时间:2014-01-16 01:23:03

标签: java arrays string collections set

我这样做了:

Set<String> mySet = new TreeSet<String>();
String list = ("word,another,word2"); // actually this is much bigger
String[] wordArr = list.split(",");
mySet.addAll(wordArr);

这会出错:

 The method addAll(Collection<? extends String>) in the type Set<String> is
 not applicable for the arguments (String[])

我认为我的意图很清楚。

问题:是否有更好的方法来实现我想要的设置?我知道我的名单中没有重复的值。

2 个答案:

答案 0 :(得分:4)

TreeSet构造函数接受CollectionString[]可以转换为使用List实现Collection的{​​{1}}。

Arrays.asList()

答案 1 :(得分:1)

以下是使用Guava的示例:

package com.sandbox;


import com.google.common.collect.Sets;

import java.util.Set;

public class Sandbox {

    public static void main(String[] args) {
        String list = ("word,another,word2"); // actually this is much bigger
        String[] wordArr = list.split(",");
        Set<String> mySet = Sets.newHashSet(wordArr);
    }        
}

如果你想在没有Arrays的情况下这样做(我不推荐,但你在课堂上,所以也许你不能使用它):

package com.sandbox;


import java.util.Set;
import java.util.TreeSet;

public class Sandbox {

    public static void main(String[] args) {
        Set<String> mySet = new TreeSet<String>();
        String list = ("word,another,word2"); // actually this is much bigger
        String[] wordArr = list.split(",");
        for (String s : wordArr) {
            mySet.add(s);
        }
    }


}