我需要创建一个具有初始值的集合。

Set<String> h = new HashSet<String>();
h.add("a");
h.add("b");

是否有一种方法可以在一行代码中做到这一点?例如,它对于最终的静态字段很有用。


当前回答

如果你只有一个值,想要得到一个不可变的集合,这就足够了:

Set<String> immutableSet = Collections.singleton("a");

其他回答

import com.google.common.collect.Sets;
Sets.newHashSet("a", "b");

or

import com.google.common.collect.ImmutableSet;
ImmutableSet.of("a", "b");

最方便的方法之一是使用泛型Collections.addAll()方法,该方法接受一个集合和可变参数:

Set<String> h = new HashSet<String>();
Collections.addAll(h, "a", "b");

有点复杂,但可以在Java 5中工作:

Set<String> h = new HashSet<String>(Arrays.asList(new String[] {  
    "a", "b"
}))

使用helper方法使其可读:

Set<String> h = asSet ("a", "b");

public Set<String> asSet(String... values) {
    return new HashSet<String>(java.util.Arrays.asList(values));
}

随着java9和方便的工厂方法的发布,这可以以一种更干净的方式实现:

Set set = Set.of("a", "b", "c");

集合字面值计划在Java 7中使用,但最终没有加入。所以还没有自动的东西。

你可以使用番石榴的套装:

Sets.newHashSet("a", "b", "c")

或者你可以使用下面的语法,这将创建一个匿名类,但它是hack:

Set<String> h = new HashSet<String>() {{
    add("a");
    add("b");
}};