我想在Java中将数组转换为Set。有一些明显的方法可以做到这一点(即使用循环),但我想做一些更整洁的事情,比如:

java.util.Arrays.asList(Object[] a);

有什么想法吗?


当前回答

有时使用一些标准库会有很大帮助。尝试查看Apache Commons集合。在这种情况下,您的问题简单地转化为以下内容

String[] keys = {"blah", "blahblah"}
Set<String> myEmptySet = new HashSet<String>();
CollectionUtils.addAll(pythonKeywordSet, keys);

这里是CollectionsUtils javadoc

其他回答

使用stanford-stagger-3.0.jar中的CollectionUtils或ArrayUtils

import static edu.stanford.nlp.util.ArrayUtils.asSet;
or 
import static edu.stanford.nlp.util.CollectionUtils.asSet;

  ...
String [] array = {"1", "q"};
Set<String> trackIds = asSet(array);

我根据上面的建议写了下面的内容——偷吧……真不错!

/**
 * Handy conversion to set
 */
public class SetUtil {
    /**
     * Convert some items to a set
     * @param items items
     * @param <T> works on any type
     * @return a hash set of the input items
     */
    public static <T> Set<T> asSet(T ... items) {
        return Stream.of(items).collect(Collectors.toSet());
    }
}

已经有很多很好的答案了,但大多数答案都不适用于基元数组(如int[]、long[]、char[]、byte[]等)

在Java 8及更高版本中,您可以使用以下命令对阵列进行装箱:

Integer[] boxedArr = Arrays.stream(arr).boxed().toArray(Integer[]::new);

然后使用流转换为集合:

Stream.of(boxedArr).collect(Collectors.toSet());

在完成Arrays.asList(array)之后,可以执行Setset=newHashSet(list);

下面是一个示例方法,您可以编写:

public <T> Set<T> GetSetFromArray(T[] array) {
    return new HashSet<T>(Arrays.asList(array));
}

有时使用一些标准库会有很大帮助。尝试查看Apache Commons集合。在这种情况下,您的问题简单地转化为以下内容

String[] keys = {"blah", "blahblah"}
Set<String> myEmptySet = new HashSet<String>();
CollectionUtils.addAll(pythonKeywordSet, keys);

这里是CollectionsUtils javadoc