如何通过构造初始化HashSet值?

时间:2022-09-25 12:58:48

I need to create a Set with initial values.

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

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

Is there a way to do this in one line of code?

是否有办法在一行代码中做到这一点?

22 个解决方案

#1


628  

There is a shorthand that I use that is not very time efficient, but fits on a single line:

有一种速记法,我用它不是很有效率,而是适合于一行:

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

Again, this is not time efficient since you are constructing an array, converting to a list and using that list to create a set.

同样,这不是时间效率,因为您正在构造一个数组,转换到一个列表并使用该列表来创建一个集合。

When initializing static final sets I usually write it like this:

当初始化静态最终集时,我通常这样写:

public static final String[] SET_VALUES = new String[] { "a", "b" };
public static final Set<String> MY_SET = new HashSet<>(Arrays.asList(SET_VALUES));

Slightly less ugly and efficiency does not matter for the static initialization.

稍微不那么丑陋和效率不影响静态初始化。

#2


266  

Collection literals were scheduled for Java 7, but didn't make it in. So nothing automatic yet.

集合文字被安排在Java 7中,但是没有成功。所以还没有自动。

You can use guava's Sets:

你可以使用番石榴的组合:

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

Or you can use the following syntax, which will create an anonymous class, but it's hacky:

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

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

#3


128  

In Java 8 I would use:

在Java 8中,我将使用:

Set<String> set = Stream.of("a", "b").collect(Collectors.toSet());

This gives you a mutable Set pre-initialized with "a" and "b". Note that while in JDK 8 this does return a HashSet, the specification doesn't guarantee it, and this might change in the future. If you specifically want a HashSet, do this instead:

这将给您一个具有“a”和“b”的易变集。注意,在JDK 8中,这确实返回了一个HashSet,但该规范并不能保证它,而且将来可能会发生变化。如果您特别想要一个HashSet,那么可以这样做:

Set<String> set = Stream.of("a", "b")
                        .collect(Collectors.toCollection(HashSet::new));

#4


74  

There are a few ways:

有几种方法:

Double brace initialization

双支撑初始化

This is a technique which creates an anonymous inner class which has an instance initializer which adds Strings to itself when an instance is created:

这是一种创建匿名内部类的技术,它有一个实例初始化器,它在创建实例时为自己添加字符串:

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

Keep in mind that this will actually create an new subclass of HashSet each time it is used, even though one does not have to explicitly write a new subclass.

请记住,这实际上会在每次使用时创建一个新的HashSet子类,即使您不必显式地编写新的子类。

A utility method

一个实用程序方法

Writing a method that returns a Set which is initialized with the desired elements isn't too hard to write:

编写一个方法,它返回一个用所需元素初始化的集合,这并不难写:

public static Set<String> newHashSet(String... strings) {
    HashSet<String> set = new HashSet<String>();

    for (String s : strings) {
        set.add(s);
    }
    return set;
}

The above code only allows for a use of a String, but it shouldn't be too difficult to allow the use of any type using generics.

上面的代码只允许使用字符串,但是允许使用泛型使用任何类型都不太困难。

Use a library

使用一个图书馆

Many libraries have a convenience method to initialize collections objects.

许多库都有一个方便的方法来初始化集合对象。

For example, Google Collections has a Sets.newHashSet(T...) method which will populate a HashSet with elements of a specific type.

例如,谷歌集合有一个Sets.newHashSet(T.)方法,它将使用特定类型的元素填充HashSet。

#5


46  

Using Java 8 (Modifiable Sets)

Using Stream in Java 8.

在Java 8中使用流。

Set<String> strSet1 = Stream.of("A", "B", "C", "D")
         .collect(Collectors.toCollection(HashSet::new));

// stream from an array (String[] stringArray)
Set<String> strSet2 = Arrays.stream(stringArray)
         .collect(Collectors.toCollection(HashSet::new));

// stream from a list (List<String> stringList)
Set<String> strSet3 = stringList.stream()
         .collect(Collectors.toCollection(HashSet::new));

Using Java 8 (Unmodifiable Sets)

Using Collections.unmodifiableSet - We can use Collections.unmodifiableSet as:

使用集合。unmodifiableSet -我们可以使用集合。unmodifiableSet:

Set<String> strSet4 = Collections.unmodifiableSet(strSet1);

But it looks slightly awkward and we can write our own collector like this:

但它看起来有点尴尬,我们可以这样写自己的收集器:

class ImmutableCollector {
    public static <T> Collector<T, Set<T>, Set<T>> toImmutableSet() {
        return Collector.of(HashSet::new, Set::add, (l, r) -> {
            l.addAll(r);
            return l;
        }, Collections::unmodifiablSet);
    }
}

And then use it as:

然后把它用作:

Set<String> strSet4 = Stream.of("A", "B", "C", "D")
             .collect(ImmutableCollector.toImmutableSet());

Using Collectors.collectingAndThen - Another approach is to use the method Collectors.collectingAndThen which lets us perform additional finishing transformations:

使用收藏家。collectingAndThen——另一种方法是使用方法收集器。然后让我们执行额外的完成转换:

import static java.util.stream.Collectors.*;
Set<String> strSet5 = Stream.of("A", "B", "C", "D").collect(collectingAndThen(
   toCollection(HashSet::new),Collections::unmodifiableSet));

If we only care about Set then we can also use Collectors.toSet() in place of Collectors.toCollection(HashSet::new).

如果我们只关心Set,那么我们也可以使用Collectors.toSet()代替Collectors.toCollection(HashSet::new)。

Using Java 9 (Unmodifiable Sets)

Set<String> strSet5 = Set.of("Apple", "Ball", "Cat", "Dog");

#6


26  

You can do it in Java 6:

你可以用Java 6:

Set<String> h = new HashSet<String>(Arrays.asList("a", "b", "c"));

But why? I don't find it to be more readable than explicitly adding elements.

但是为什么呢?我不认为它比显式添加元素更容易阅读。

#7


23  

If you have only one initial value in set this would be enough:

如果你只有一个初始值,这就足够了:

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

#8


19  

I feel the most readable is to simply use google Guava:

我觉得最易读的就是使用谷歌番石榴:

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

#9


14  

A generalization of coobird's answer's utility function for creating new HashSets:

coobird的答案对创建新hashset的效用函数的一般化:

public static <T> Set<T> newHashSet(T... objs) {
    Set<T> set = new HashSet<T>();
    for (T o : objs) {
        set.add(o);
    }
    return set;
}

#10


12  

With Java 9 you can do the following:

使用Java 9,您可以执行以下操作:

Set.of("a", "b");

and you'll get an immutable Set containing the elements. For details see the Oracle documentation of interface Set.

你会得到一个包含元素的不可变集。有关详细信息,请参阅接口集的Oracle文档。

#11


11  

One of the most convenient ways is usage of generic Collections.addAll() method, which takes a collection and varargs:

最方便的方法之一是使用通用的Collections.addAll()方法,它采用集合和varargs:

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

#12


8  

If the contained type of the Set is an enumeration then there is java built factory method (since 1.5):

如果集合的包含类型是枚举,那么就有java构建的工厂方法(自1.5):

Set<MY_ENUM> MY_SET = EnumSet.of( MY_ENUM.value1, MY_ENUM.value2, ... );

#13


5  

With Eclipse Collections there are a few different ways to initialize a Set containing the characters 'a' and 'b' in one statement. Eclipse Collections has containers for both object and primitive types, so I illustrated how you could use a Set<String> or CharSet in addition to mutable, immutable, synchronized and unmodifiable versions of both.

在Eclipse集合中,有几种不同的方法来初始化一个包含字符a和b的集合。Eclipse集合有对象和基本类型的容器,所以我演示了如何使用Set 或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 is compatible with Java 5 - 8.

Eclipse集合与Java 5 - 8兼容。

Note: I am a committer for Eclipse Collections.

注意:我是Eclipse集合的提交者。

#14


4  

A bit convoluted but works from Java 5:

有点复杂,但从Java 5工作:

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

Use a helper method to make it readable:

使用辅助方法使其可读:

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

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

#15


3  

Just a small note, regardless of which of the fine approaches mentioned here you end up with, if this is a default that usually goes unmodified (like a default setting in a library you are creating), it is a good idea to follow this pattern:

只是一个小提示,不管前面提到的那些细微的方法是什么,如果这是默认的,通常不会被修改(比如在创建的库中默认设置),那么遵循这个模式是一个好主意:

// Initialize default values with the method you prefer, even in a static block
// It's a good idea to make sure these defaults aren't modifiable
private final static Set<String> DEFAULT_VALUES = Collections.unmodifiableSet(...);
private Set<String> values = DEFAULT_VALUES;

The benefit depends on the number of instances you create of that class and how likely it's that defaults will be changed.

它的好处取决于您创建该类的实例的数量,以及它的默认值有多大可能发生更改。

If you decide to follow this pattern, then you also get to pick the method of set initialization that's most readable. As the micro differences in efficiency between the different methods will probably not matter much as you will be initializing the set only once.

如果您决定遵循这个模式,那么您还可以选择最易读的设置初始化方法。由于不同方法之间效率的微小差异可能并不重要,因为您只需要初始化设置一次。

#16


3  

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

or

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

#17


2  

(ugly) Double Brace Initialization without side effects:

(丑陋)双支架初始化,无副作用:

Set<String> a = new HashSet<>(new HashSet<String>() {{
    add("1");
    add("2");
}})

But in some cases, if we mentioned that is a good smell to make final collections unmutable, it could be really useful:

但在某些情况下,如果我们提到这是一种很好的气味来让最终的集合不可变,它可能非常有用:

final Set<String> a = Collections.unmodifiableSet(new HashSet<String>(){{
    add("1");
    add("2");
}})

#18


2  

Using Java 8 we can create HashSet as:

使用Java 8,我们可以创建HashSet:

Stream.of("A", "B", "C", "D").collect(Collectors.toCollection(HashSet::new));

And if we want unmodifiable set we can create a utility method as :

如果我们想要无法修改的集合我们可以创建一个实用的方法

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);
    }

This method can be used as :

该方法可用于:

 Stream.of("A", "B", "C", "D").collect(toImmutableSet(HashSet::new));

#19


1  

With the release of and the convenience factory methods this is possible in a cleaner way as:

随着java9的发布和方便的工厂方法,这是可能的更清洁的方式:

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

#20


0  

This is an elegant solution:

这是一个优雅的解决方案:

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);
            }
        };
}

#21


0  

Can use static block for initialization:

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

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

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

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

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

#22


0  

The Builder pattern might be of use here. Today I had the same issue. where I needed Set mutating operations to return me a reference of the Set object, so I can pass it to super class constructor so that they too can continue adding to same set by in turn constructing a new StringSetBuilder off of the Set that the child class just built. The builder class I wrote looks like this (in my case it's a static inner class of an outer class, but it can be its own independent class as well):

生成器模式可能在这里使用。今天我遇到了同样的问题。我需要组变异操作返回我的对象的引用,所以我可以将它传递给超类的构造函数,这样他们也可以继续添加同一组,进而构造一个新的StringSetBuilder的子类就建立的集合。我编写的builder类是这样的(在我的例子中,它是一个外部类的静态内部类,但是它也可以是它自己的独立类):

public interface Builder<T> {
    T build();
}

static class StringSetBuilder implements Builder<Set<String>> {
    private final Set<String> set = new HashSet<>();

    StringSetBuilder add(String pStr) {
        set.add(pStr);
        return this;
    }

    StringSetBuilder addAll(Set<String> pSet) {
        set.addAll(pSet);
        return this;
    }

    @Override
    public Set<String> build() {
        return set;
    }
}

Notice the addAll() and add() methods, which are Set returning counterparts of Set.add() and Set.addAll(). Finally notice the build() method, which returns a reference to the Set that the builder encapsulates. Below illustrates then how to use this Set builder:

注意addAll()和add()方法,这些方法将返回Set.add()和Set.addAll()的对应函数。最后,请注意build()方法,该方法返回对构建器封装的集合的引用。下面说明如何使用这个Set builder:

class SomeChildClass extends ParentClass {
    public SomeChildClass(String pStr) {
        super(new StringSetBuilder().add(pStr).build());
    }
}

class ParentClass {
    public ParentClass(Set<String> pSet) {
        super(new StringSetBuilder().addAll(pSet).add("my own str").build());
    }
}

#1


628  

There is a shorthand that I use that is not very time efficient, but fits on a single line:

有一种速记法,我用它不是很有效率,而是适合于一行:

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

Again, this is not time efficient since you are constructing an array, converting to a list and using that list to create a set.

同样,这不是时间效率,因为您正在构造一个数组,转换到一个列表并使用该列表来创建一个集合。

When initializing static final sets I usually write it like this:

当初始化静态最终集时,我通常这样写:

public static final String[] SET_VALUES = new String[] { "a", "b" };
public static final Set<String> MY_SET = new HashSet<>(Arrays.asList(SET_VALUES));

Slightly less ugly and efficiency does not matter for the static initialization.

稍微不那么丑陋和效率不影响静态初始化。

#2


266  

Collection literals were scheduled for Java 7, but didn't make it in. So nothing automatic yet.

集合文字被安排在Java 7中,但是没有成功。所以还没有自动。

You can use guava's Sets:

你可以使用番石榴的组合:

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

Or you can use the following syntax, which will create an anonymous class, but it's hacky:

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

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

#3


128  

In Java 8 I would use:

在Java 8中,我将使用:

Set<String> set = Stream.of("a", "b").collect(Collectors.toSet());

This gives you a mutable Set pre-initialized with "a" and "b". Note that while in JDK 8 this does return a HashSet, the specification doesn't guarantee it, and this might change in the future. If you specifically want a HashSet, do this instead:

这将给您一个具有“a”和“b”的易变集。注意,在JDK 8中,这确实返回了一个HashSet,但该规范并不能保证它,而且将来可能会发生变化。如果您特别想要一个HashSet,那么可以这样做:

Set<String> set = Stream.of("a", "b")
                        .collect(Collectors.toCollection(HashSet::new));

#4


74  

There are a few ways:

有几种方法:

Double brace initialization

双支撑初始化

This is a technique which creates an anonymous inner class which has an instance initializer which adds Strings to itself when an instance is created:

这是一种创建匿名内部类的技术,它有一个实例初始化器,它在创建实例时为自己添加字符串:

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

Keep in mind that this will actually create an new subclass of HashSet each time it is used, even though one does not have to explicitly write a new subclass.

请记住,这实际上会在每次使用时创建一个新的HashSet子类,即使您不必显式地编写新的子类。

A utility method

一个实用程序方法

Writing a method that returns a Set which is initialized with the desired elements isn't too hard to write:

编写一个方法,它返回一个用所需元素初始化的集合,这并不难写:

public static Set<String> newHashSet(String... strings) {
    HashSet<String> set = new HashSet<String>();

    for (String s : strings) {
        set.add(s);
    }
    return set;
}

The above code only allows for a use of a String, but it shouldn't be too difficult to allow the use of any type using generics.

上面的代码只允许使用字符串,但是允许使用泛型使用任何类型都不太困难。

Use a library

使用一个图书馆

Many libraries have a convenience method to initialize collections objects.

许多库都有一个方便的方法来初始化集合对象。

For example, Google Collections has a Sets.newHashSet(T...) method which will populate a HashSet with elements of a specific type.

例如,谷歌集合有一个Sets.newHashSet(T.)方法,它将使用特定类型的元素填充HashSet。

#5


46  

Using Java 8 (Modifiable Sets)

Using Stream in Java 8.

在Java 8中使用流。

Set<String> strSet1 = Stream.of("A", "B", "C", "D")
         .collect(Collectors.toCollection(HashSet::new));

// stream from an array (String[] stringArray)
Set<String> strSet2 = Arrays.stream(stringArray)
         .collect(Collectors.toCollection(HashSet::new));

// stream from a list (List<String> stringList)
Set<String> strSet3 = stringList.stream()
         .collect(Collectors.toCollection(HashSet::new));

Using Java 8 (Unmodifiable Sets)

Using Collections.unmodifiableSet - We can use Collections.unmodifiableSet as:

使用集合。unmodifiableSet -我们可以使用集合。unmodifiableSet:

Set<String> strSet4 = Collections.unmodifiableSet(strSet1);

But it looks slightly awkward and we can write our own collector like this:

但它看起来有点尴尬,我们可以这样写自己的收集器:

class ImmutableCollector {
    public static <T> Collector<T, Set<T>, Set<T>> toImmutableSet() {
        return Collector.of(HashSet::new, Set::add, (l, r) -> {
            l.addAll(r);
            return l;
        }, Collections::unmodifiablSet);
    }
}

And then use it as:

然后把它用作:

Set<String> strSet4 = Stream.of("A", "B", "C", "D")
             .collect(ImmutableCollector.toImmutableSet());

Using Collectors.collectingAndThen - Another approach is to use the method Collectors.collectingAndThen which lets us perform additional finishing transformations:

使用收藏家。collectingAndThen——另一种方法是使用方法收集器。然后让我们执行额外的完成转换:

import static java.util.stream.Collectors.*;
Set<String> strSet5 = Stream.of("A", "B", "C", "D").collect(collectingAndThen(
   toCollection(HashSet::new),Collections::unmodifiableSet));

If we only care about Set then we can also use Collectors.toSet() in place of Collectors.toCollection(HashSet::new).

如果我们只关心Set,那么我们也可以使用Collectors.toSet()代替Collectors.toCollection(HashSet::new)。

Using Java 9 (Unmodifiable Sets)

Set<String> strSet5 = Set.of("Apple", "Ball", "Cat", "Dog");

#6


26  

You can do it in Java 6:

你可以用Java 6:

Set<String> h = new HashSet<String>(Arrays.asList("a", "b", "c"));

But why? I don't find it to be more readable than explicitly adding elements.

但是为什么呢?我不认为它比显式添加元素更容易阅读。

#7


23  

If you have only one initial value in set this would be enough:

如果你只有一个初始值,这就足够了:

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

#8


19  

I feel the most readable is to simply use google Guava:

我觉得最易读的就是使用谷歌番石榴:

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

#9


14  

A generalization of coobird's answer's utility function for creating new HashSets:

coobird的答案对创建新hashset的效用函数的一般化:

public static <T> Set<T> newHashSet(T... objs) {
    Set<T> set = new HashSet<T>();
    for (T o : objs) {
        set.add(o);
    }
    return set;
}

#10


12  

With Java 9 you can do the following:

使用Java 9,您可以执行以下操作:

Set.of("a", "b");

and you'll get an immutable Set containing the elements. For details see the Oracle documentation of interface Set.

你会得到一个包含元素的不可变集。有关详细信息,请参阅接口集的Oracle文档。

#11


11  

One of the most convenient ways is usage of generic Collections.addAll() method, which takes a collection and varargs:

最方便的方法之一是使用通用的Collections.addAll()方法,它采用集合和varargs:

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

#12


8  

If the contained type of the Set is an enumeration then there is java built factory method (since 1.5):

如果集合的包含类型是枚举,那么就有java构建的工厂方法(自1.5):

Set<MY_ENUM> MY_SET = EnumSet.of( MY_ENUM.value1, MY_ENUM.value2, ... );

#13


5  

With Eclipse Collections there are a few different ways to initialize a Set containing the characters 'a' and 'b' in one statement. Eclipse Collections has containers for both object and primitive types, so I illustrated how you could use a Set<String> or CharSet in addition to mutable, immutable, synchronized and unmodifiable versions of both.

在Eclipse集合中,有几种不同的方法来初始化一个包含字符a和b的集合。Eclipse集合有对象和基本类型的容器,所以我演示了如何使用Set 或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 is compatible with Java 5 - 8.

Eclipse集合与Java 5 - 8兼容。

Note: I am a committer for Eclipse Collections.

注意:我是Eclipse集合的提交者。

#14


4  

A bit convoluted but works from Java 5:

有点复杂,但从Java 5工作:

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

Use a helper method to make it readable:

使用辅助方法使其可读:

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

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

#15


3  

Just a small note, regardless of which of the fine approaches mentioned here you end up with, if this is a default that usually goes unmodified (like a default setting in a library you are creating), it is a good idea to follow this pattern:

只是一个小提示,不管前面提到的那些细微的方法是什么,如果这是默认的,通常不会被修改(比如在创建的库中默认设置),那么遵循这个模式是一个好主意:

// Initialize default values with the method you prefer, even in a static block
// It's a good idea to make sure these defaults aren't modifiable
private final static Set<String> DEFAULT_VALUES = Collections.unmodifiableSet(...);
private Set<String> values = DEFAULT_VALUES;

The benefit depends on the number of instances you create of that class and how likely it's that defaults will be changed.

它的好处取决于您创建该类的实例的数量,以及它的默认值有多大可能发生更改。

If you decide to follow this pattern, then you also get to pick the method of set initialization that's most readable. As the micro differences in efficiency between the different methods will probably not matter much as you will be initializing the set only once.

如果您决定遵循这个模式,那么您还可以选择最易读的设置初始化方法。由于不同方法之间效率的微小差异可能并不重要,因为您只需要初始化设置一次。

#16


3  

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

or

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

#17


2  

(ugly) Double Brace Initialization without side effects:

(丑陋)双支架初始化,无副作用:

Set<String> a = new HashSet<>(new HashSet<String>() {{
    add("1");
    add("2");
}})

But in some cases, if we mentioned that is a good smell to make final collections unmutable, it could be really useful:

但在某些情况下,如果我们提到这是一种很好的气味来让最终的集合不可变,它可能非常有用:

final Set<String> a = Collections.unmodifiableSet(new HashSet<String>(){{
    add("1");
    add("2");
}})

#18


2  

Using Java 8 we can create HashSet as:

使用Java 8,我们可以创建HashSet:

Stream.of("A", "B", "C", "D").collect(Collectors.toCollection(HashSet::new));

And if we want unmodifiable set we can create a utility method as :

如果我们想要无法修改的集合我们可以创建一个实用的方法

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);
    }

This method can be used as :

该方法可用于:

 Stream.of("A", "B", "C", "D").collect(toImmutableSet(HashSet::new));

#19


1  

With the release of and the convenience factory methods this is possible in a cleaner way as:

随着java9的发布和方便的工厂方法,这是可能的更清洁的方式:

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

#20


0  

This is an elegant solution:

这是一个优雅的解决方案:

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);
            }
        };
}

#21


0  

Can use static block for initialization:

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

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

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

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

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

#22


0  

The Builder pattern might be of use here. Today I had the same issue. where I needed Set mutating operations to return me a reference of the Set object, so I can pass it to super class constructor so that they too can continue adding to same set by in turn constructing a new StringSetBuilder off of the Set that the child class just built. The builder class I wrote looks like this (in my case it's a static inner class of an outer class, but it can be its own independent class as well):

生成器模式可能在这里使用。今天我遇到了同样的问题。我需要组变异操作返回我的对象的引用,所以我可以将它传递给超类的构造函数,这样他们也可以继续添加同一组,进而构造一个新的StringSetBuilder的子类就建立的集合。我编写的builder类是这样的(在我的例子中,它是一个外部类的静态内部类,但是它也可以是它自己的独立类):

public interface Builder<T> {
    T build();
}

static class StringSetBuilder implements Builder<Set<String>> {
    private final Set<String> set = new HashSet<>();

    StringSetBuilder add(String pStr) {
        set.add(pStr);
        return this;
    }

    StringSetBuilder addAll(Set<String> pSet) {
        set.addAll(pSet);
        return this;
    }

    @Override
    public Set<String> build() {
        return set;
    }
}

Notice the addAll() and add() methods, which are Set returning counterparts of Set.add() and Set.addAll(). Finally notice the build() method, which returns a reference to the Set that the builder encapsulates. Below illustrates then how to use this Set builder:

注意addAll()和add()方法,这些方法将返回Set.add()和Set.addAll()的对应函数。最后,请注意build()方法,该方法返回对构建器封装的集合的引用。下面说明如何使用这个Set builder:

class SomeChildClass extends ParentClass {
    public SomeChildClass(String pStr) {
        super(new StringSetBuilder().add(pStr).build());
    }
}

class ParentClass {
    public ParentClass(Set<String> pSet) {
        super(new StringSetBuilder().addAll(pSet).add("my own str").build());
    }
}