我需要创建一个具有初始值的集合。
Set<String> h = new HashSet<String>();
h.add("a");
h.add("b");
是否有一种方法可以在一行代码中做到这一点?例如,它对于最终的静态字段很有用。
我需要创建一个具有初始值的集合。
Set<String> h = new HashSet<String>();
h.add("a");
h.add("b");
是否有一种方法可以在一行代码中做到这一点?例如,它对于最终的静态字段很有用。
当前回答
import com.google.common.collect.Sets;
Sets.newHashSet("a", "b");
or
import com.google.common.collect.ImmutableSet;
ImmutableSet.of("a", "b");
其他回答
你可以在Java 6中做到:
Set<String> h = new HashSet<String>(Arrays.asList("a", "b", "c"));
但是为什么呢?我不认为它比显式地添加元素更具有可读性。
import com.google.common.collect.Sets;
Sets.newHashSet("a", "b");
or
import com.google.common.collect.ImmutableSet;
ImmutableSet.of("a", "b");
使用Java 9,你可以做到以下几点:
Set.of("a", "b");
你会得到一个包含元素的不可变集合。具体操作请参见接口Set的Oracle文档。
我觉得最有可读性的是简单地使用谷歌番石榴:
Set<String> StringSet = Sets.newHashSet("a", "b", "c");
这是可变的。
在Eclipse Collections中,有几种不同的方法来初始化一个包含字符'a'和'b'的Set语句。Eclipse Collections同时为对象类型和基本类型提供了容器,因此我演示了如何使用Set<String>或CharSet,以及可变、不可变、同步和不可修改的这两个版本。
Set<String> set =
Sets.mutable.with("a", "b");
HashSet<String> hashSet =
Sets.mutable.with("a", "b").asLazy().into(new HashSet<String>());
Set<String> synchronizedSet =
Sets.mutable.with("a", "b").asSynchronized();
Set<String> unmodifiableSet =
Sets.mutable.with("a", "b").asUnmodifiable();
MutableSet<String> mutableSet =
Sets.mutable.with("a", "b");
MutableSet<String> synchronizedMutableSet =
Sets.mutable.with("a", "b").asSynchronized();
MutableSet<String> unmodifiableMutableSet =
Sets.mutable.with("a", "b").asUnmodifiable();
ImmutableSet<String> immutableSet =
Sets.immutable.with("a", "b");
ImmutableSet<String> immutableSet2 =
Sets.mutable.with("a", "b").toImmutable();
CharSet charSet =
CharSets.mutable.with('a', 'b');
CharSet synchronizedCharSet =
CharSets.mutable.with('a', 'b').asSynchronized();
CharSet unmodifiableCharSet =
CharSets.mutable.with('a', 'b').asUnmodifiable();
MutableCharSet mutableCharSet =
CharSets.mutable.with('a', 'b');
ImmutableCharSet immutableCharSet =
CharSets.immutable.with('a', 'b');
ImmutableCharSet immutableCharSet2 =
CharSets.mutable.with('a', 'b').toImmutable();
注意:我是Eclipse Collections的提交者。