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

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

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


当前回答

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

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

其他回答

你也可以使用vavr:

import io.vavr.collection.HashSet;

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

or

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

我觉得最有可读性的是简单地使用谷歌番石榴:

Set<String> StringSet = Sets.newHashSet("a", "b", "c");

这是可变的。

可以使用静态块进行初始化:

private static Set<Integer> codes1=
        new HashSet<Integer>(Arrays.asList(1, 2, 3, 4));

private static Set<Integer> codes2 =
        new HashSet<Integer>(Arrays.asList(5, 6, 7, 8));

private static Set<Integer> h = new HashSet<Integer>();

static{
    h.add(codes1);
    h.add(codes2);
}

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

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