我需要创建一个具有初始值的集合。
Set<String> h = new HashSet<String>();
h.add("a");
h.add("b");
是否有一种方法可以在一行代码中做到这一点?例如,它对于最终的静态字段很有用。
我需要创建一个具有初始值的集合。
Set<String> h = new HashSet<String>();
h.add("a");
h.add("b");
是否有一种方法可以在一行代码中做到这一点?例如,它对于最终的静态字段很有用。
当前回答
如果Set的包含类型是枚举类型,则存在java构建的工厂方法(从1.5开始):
Set<MY_ENUM> MY_SET = EnumSet.of( MY_ENUM.value1, MY_ENUM.value2, ... );
其他回答
(丑陋)双大括号初始化没有副作用:
Set<String> a = new HashSet<>(new HashSet<String>() {{
add("1");
add("2");
}})
但在某些情况下,如果我们提到这是一个使最终集合不可变的好味道,它可能真的很有用:
final Set<String> a = Collections.unmodifiableSet(new HashSet<String>(){{
add("1");
add("2");
}})
你可以在Java 6中做到:
Set<String> h = new HashSet<String>(Arrays.asList("a", "b", "c"));
但是为什么呢?我不认为它比显式地添加元素更具有可读性。
使用Java 8,我们可以创建HashSet为:
Stream.of("A", "B", "C", "D").collect(Collectors.toCollection(HashSet::new));
如果我们想要不可修改的集合,我们可以创建一个实用方法:
public static <T, A extends Set<T>> Collector<T, A, Set<T>> toImmutableSet(Supplier<A> supplier) {
return Collector.of(
supplier,
Set::add, (left, right) -> {
left.addAll(right);
return left;
}, Collections::unmodifiableSet);
}
此方法可用于:
Stream.of("A", "B", "C", "D").collect(toImmutableSet(HashSet::new));
我觉得最有可读性的是简单地使用谷歌番石榴:
Set<String> StringSet = Sets.newHashSet("a", "b", "c");
这是可变的。
这是一个优雅的解决方案:
public static final <T> Set<T> makeSet(@SuppressWarnings("unchecked") T... o) {
return new HashSet<T>() {
private static final long serialVersionUID = -3634958843858172518L;
{
for (T x : o)
add(x);
}
};
}