Java中如何将数组转换为集合

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3064423/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 16:09:03  来源:igfitidea点击:

How to convert an Array to a Set in Java

javacollectionsarraysset

提问by

I would like to convert an array to a Set in Java. There are some obvious ways of doing this (i.e. with a loop) but I would like something a bit neater, something like:

我想在 Java 中将数组转换为 Set。有一些明显的方法可以做到这一点(即使用循环),但我想要更简洁的东西,例如:

java.util.Arrays.asList(Object[] a);

Any ideas?

有任何想法吗?

采纳答案by SLaks

Like this:

像这样:

Set<T> mySet = new HashSet<>(Arrays.asList(someArray));

In Java 9+, if unmodifiable set is ok:

在 Java 9+ 中,如果不可修改的集合是可以的:

Set<T> mySet = Set.of(someArray);

In Java 10+, the generic type parameter can be inferred from the arrays component type:

在 Java 10+ 中,可以从数组组件类型推断泛型类型参数:

var mySet = Set.of(someArray);

回答by Petar Minchev

After you do Arrays.asList(array)you can execute Set set = new HashSet(list);

完成后Arrays.asList(array)你可以执行Set set = new HashSet(list);

Here is a sample method, you can write:

这是一个示例方法,您可以编写:

public <T> Set<T> GetSetFromArray(T[] array) {
    return new HashSet<T>(Arrays.asList(array));
}

回答by Ben S

new HashSet<Object>(Arrays.asList(Object[] a));

new HashSet<Object>(Arrays.asList(Object[] a));

But I think this would be more efficient:

但我认为这会更有效率:

final Set s = new HashSet<Object>();    
for (Object o : a) { s.add(o); }         

回答by ColinD

With Guavayou can do:

使用番石榴,您可以:

T[] array = ...
Set<T> set = Sets.newHashSet(array);

回答by JavadocMD

Set<T> mySet = new HashSet<T>();
Collections.addAll(mySet, myArray);

That's Collections.addAll(java.util.Collection, T...)from JDK 6.

那是JDK 6Collections.addAll(java.util.Collection, T...)

Additionally: what if our array is full of primitives?

另外:如果我们的数组充满了原语怎么办?

For JDK < 8, I would just write the obvious forloop to do the wrap and add-to-set in one pass.

对于 JDK < 8,我只会编写明显的for循环来一次性完成包装和添加设置。

For JDK >= 8, an attractive option is something like:

对于 JDK >= 8,一个有吸引力的选项是:

Arrays.stream(intArray).boxed().collect(Collectors.toSet());

回答by Pierre-Olivier Pignon

Quickly : you can do :

快速:您可以:

// Fixed-size list
List list = Arrays.asList(array);

// Growable list
list = new LinkedList(Arrays.asList(array));

// Duplicate elements are discarded
Set set = new HashSet(Arrays.asList(array));

and to reverse

并扭转

// Create an array containing the elements in a list
Object[] objectArray = list.toArray();
MyClass[] array = (MyClass[])list.toArray(new MyClass[list.size()]);

// Create an array containing the elements in a set
objectArray = set.toArray();
array = (MyClass[])set.toArray(new MyClass[set.size()]);

回答by mnagni

Sometime using some standard libraries helps a lot. Try to look at the Apache Commons Collections. In this case your problems is simply transformed to something like this

有时使用一些标准库会有很大帮助。尝试查看Apache Commons Collections。在这种情况下,您的问题只是转化为这样的

String[] keys = {"blah", "blahblah"}
Set<String> myEmptySet = new HashSet<String>();
CollectionUtils.addAll(pythonKeywordSet, keys);

And here is the CollectionsUtils javadoc

这是CollectionsUtils javadoc

回答by Donald Raab

In Eclipse Collections, the following will work:

Eclipse Collections 中,以下内容将起作用:

Set<Integer> set1 = Sets.mutable.of(1, 2, 3, 4, 5);
Set<Integer> set2 = Sets.mutable.of(new Integer[]{1, 2, 3, 4, 5});
MutableSet<Integer> mutableSet = Sets.mutable.of(1, 2, 3, 4, 5);
ImmutableSet<Integer> immutableSet = Sets.immutable.of(1, 2, 3, 4, 5);

Set<Integer> unmodifiableSet = Sets.mutable.of(1, 2, 3, 4, 5).asUnmodifiable();
Set<Integer> synchronizedSet = Sets.mutable.of(1, 2, 3, 4, 5).asSynchronized();
ImmutableSet<Integer> immutableSet = Sets.mutable.of(1, 2, 3, 4, 5).toImmutable();

Note: I am a committer for Eclipse Collections

注意:我是 Eclipse Collections 的提交者

回答by max

Java 8:

爪哇 8:

String[] strArray = {"eins", "zwei", "drei", "vier"};

Set<String> strSet = Arrays.stream(strArray).collect(Collectors.toSet());
System.out.println(strSet);
// [eins, vier, zwei, drei]

回答by akhil_mittal

Java 8

爪哇 8

We have the option of using Streamas well. We can get stream in various ways:

我们也可以选择使用Stream。我们可以通过多种方式获取流:

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

String[] stringArray = {"A", "B", "C", "D"};
Set<String> strSet1 = Arrays.stream(stringArray).collect(Collectors.toSet());
System.out.println(strSet1);

// if you need HashSet then use below option.
Set<String> strSet2 = Arrays.stream(stringArray).collect(Collectors.toCollection(HashSet::new));
System.out.println(strSet2);

The source code of Collectors.toSet()shows that elements are added one by one to a HashSetbut specification does not guarantee it will be a HashSet.

的源代码Collectors.toSet()显示元素一个一个地添加到 aHashSet但规范不保证它会是 a HashSet

"There are no guarantees on the type, mutability, serializability, or thread-safety of the Set returned."

“对返回的 Set 的类型、可变性、可序列化性或线程安全性没有任何保证。”

So it is better to use the later option. The output is: [A, B, C, D] [A, B, C, D] [A, B, C, D]

所以最好使用后面的选项。输出是: [A, B, C, D] [A, B, C, D] [A, B, C, D]

Immutable Set (Java 9)

不可变集 (Java 9)

Java 9 introduced Set.ofstatic factory method which returns immutable set for the provided elements or the array.

Java 9 引入了Set.of静态工厂方法,它为提供的元素或数组返回不可变的集合。

@SafeVarargs
static <E> Set<E> of?(E... elements)

Check Immutable Set Static Factory Methodsfor details.

有关详细信息,请查看不可变集静态工厂方法

Immutable Set (Java 10)

不可变集(Java 10)

We can also get an immutable set in two ways:

我们还可以通过两种方式获得一个不可变的集合:

  1. Set.copyOf(Arrays.asList(array))
  2. Arrays.stream(array).collect(Collectors.toUnmodifiableList());
  1. Set.copyOf(Arrays.asList(array))
  2. Arrays.stream(array).collect(Collectors.toUnmodifiableList());

The method Collectors.toUnmodifiableList()internally makes use of Set.ofintroduced in Java 9. Also check this answerof mine for more.

该方法Collectors.toUnmodifiableList()内部使用了Set.ofJava 9中引入的方法。另请查看我的这个答案以获取更多信息。