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

发布于 2024-09-06 05:40:49 字数 146 浏览 2 评论 0 原文

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

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

有什么想法吗?

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.util.Arrays.asList(Object[] a);

Any ideas?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(19

桃气十足 2024-09-13 05:40:50

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

但我认为这会更有效:

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

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); }         
不奢求什么 2024-09-13 05:40:50
Set<T> b = new HashSet<>(Arrays.asList(requiredArray));
Set<T> b = new HashSet<>(Arrays.asList(requiredArray));
落在眉间の轻吻 2024-09-13 05:40:49

像这样:

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

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

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

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

var mySet = Set.of(someArray);

小心

Set.of 抛出 IllegalArgumentException - 如果有任何重复项
someArray 中的元素。
查看更多详细信息: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Set.html#of(E...)


如果您想要一个不可修改的集合并且数组中可能有重复的元素,请执行以下操作:

var mySet = Set.copyOf(Arrays.asList(array));

Like this:

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

In Java 9+, if unmodifiable set is ok:

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

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

var mySet = Set.of(someArray);

Be careful

Set.of throws IllegalArgumentException - if there are any duplicate
elements in someArray.
See more details: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Set.html#of(E...)

If you want an unmodifiable set and you might have duplicate elements in the array, do the following:

var mySet = Set.copyOf(Arrays.asList(array));
热风软妹 2024-09-13 05:40:49
Set<T> mySet = new HashSet<T>();
Collections.addAll(mySet, myArray);

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

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

对于 JDK 8、我只需编写明显的 for 循环即可一次完成包装和添加到集合。

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

Arrays.stream(intArray).boxed().collect(Collectors.toSet());
Set<T> mySet = new HashSet<T>();
Collections.addAll(mySet, myArray);

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

Additionally: what if our array is full of primitives?

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

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

Arrays.stream(intArray).boxed().collect(Collectors.toSet());
朱染 2024-09-13 05:40:49

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

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

With Guava you can do:

T[] array = ...
Set<T> set = Sets.newHashSet(array);
淡淡の花香 2024-09-13 05:40:49

Java 8:

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

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

Java 8:

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

Set<String> strSet = Arrays.stream(strArray).collect(Collectors.toSet());
System.out.println(strSet);
// [eins, vier, zwei, drei]
始终不够爱げ你 2024-09-13 05:40:49

Varargs 也可以工作!

Stream.of(T... values).collect(Collectors.toSet());

Varargs will work too!

Stream.of(T... values).collect(Collectors.toSet());
拧巴小姐 2024-09-13 05:40:49

Java 8

我们也可以选择使用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);

Collectors.toSet()的源代码显示元素被逐一添加到HashSet中,但规范不保证它会被添加到HashSet中。一个HashSet

“不保证类型、可变性、可序列化性或
返回的 Set 的线程安全性。”

因此最好使用后面的选项。输出为:
<代码>
[甲、乙、丙、丁]
[甲、乙、丙、丁]
[A, B, C, D]

不可变集 (Java 9)

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

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

检查不可变设置静态工厂方法细节。

不可变集 (Java 10)

我们还可以通过两种方式获取不可变集:

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

方法 Collectors.toUnmodifyingList() 内部使用了 Java 9 中引入的 Set.of。另请检查此 我的回答了解更多信息。

Java 8

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

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 HashSet but specification does not guarantee it will be a HashSet.

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

So it is better to use the later option. The output is:

[A, B, C, D]
[A, B, C, D]
[A, B, C, D]

Immutable Set (Java 9)

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

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

Check Immutable Set Static Factory Methods for details.

Immutable Set (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());

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

携君以终年 2024-09-13 05:40:49

执行Arrays.asList(array)后,您可以执行Set set = new HashSet(list);

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

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

After you do Arrays.asList(array) you can execute 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));
}
滴情不沾 2024-09-13 05:40:49

已经有很多很好的答案,但其中大多数不适用于基元数组(例如 int[]long[]char []byte[] 等)

在 Java 8 及更高版本中,您可以使用以下方式对数组进行装箱:

Integer[] boxedArr = Arrays.stream(arr).boxed().toArray(Integer[]::new);

然后使用流转换为集合:

Stream.of(boxedArr).collect(Collectors.toSet());

There has been a lot of great answers already, but most of them won't work with array of primitives (like int[], long[], char[], byte[], etc.)

In Java 8 and above, you can box the array with:

Integer[] boxedArr = Arrays.stream(arr).boxed().toArray(Integer[]::new);

Then convert to set using stream:

Stream.of(boxedArr).collect(Collectors.toSet());
深白境迁sunset 2024-09-13 05:40:49

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

注意:我是 Eclipse Collections 的提交者

In Eclipse Collections, the following will work:

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

溺ぐ爱和你が 2024-09-13 05:40:49

快点:你可以做:

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

并逆转

// 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()]);

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()]);
谁对谁错谁最难过 2024-09-13 05:40:49

我根据上面的建议写了下面的内容 - 偷走它......这很好!

/**
 * Handy conversion to set
 */
public class SetUtil {
    /**
     * Convert some items to a set
     * @param items items
     * @param <T> works on any type
     * @return a hash set of the input items
     */
    public static <T> Set<T> asSet(T ... items) {
        return Stream.of(items).collect(Collectors.toSet());
    }
}

I've written the below from the advice above - steal it... it's nice!

/**
 * Handy conversion to set
 */
public class SetUtil {
    /**
     * Convert some items to a set
     * @param items items
     * @param <T> works on any type
     * @return a hash set of the input items
     */
    public static <T> Set<T> asSet(T ... items) {
        return Stream.of(items).collect(Collectors.toSet());
    }
}
半衾梦 2024-09-13 05:40:49

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

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

,这是 CollectionsUtils javadoc

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

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

And here is the CollectionsUtils javadoc

短叹 2024-09-13 05:40:49

使用 stanford-postagger-3.0.jar 中的 CollectionUtilsArrayUtils

import static edu.stanford.nlp.util.ArrayUtils.asSet;
or 
import static edu.stanford.nlp.util.CollectionUtils.asSet;

  ...
String [] array = {"1", "q"};
Set<String> trackIds = asSet(array);

Use CollectionUtils or ArrayUtils from stanford-postagger-3.0.jar

import static edu.stanford.nlp.util.ArrayUtils.asSet;
or 
import static edu.stanford.nlp.util.CollectionUtils.asSet;

  ...
String [] array = {"1", "q"};
Set<String> trackIds = asSet(array);
在巴黎塔顶看东京樱花 2024-09-13 05:40:49

在 Java 10 中:

String[] strs = {"A", "B"};
Set<String> set = Set.copyOf(Arrays.asList(strs));

Set.copyOf 返回一个不可修改的 Set,其中包含给定 Collection 的元素。

给定的 Collection 不得为 null,并且不得包含任何 null 元素。

In Java 10:

String[] strs = {"A", "B"};
Set<String> set = Set.copyOf(Arrays.asList(strs));

Set.copyOf returns an unmodifiable Set containing the elements of the given Collection.

 The given Collection must not be null, and it must not contain any null elements.

别把无礼当个性 2024-09-13 05:40:49
private Map<Integer, Set<Integer>> nobreaks = new HashMap();
nobreaks.put(1, new HashSet(Arrays.asList(new int[]{2, 4, 5})));
System.out.println("expected size is 3: " +nobreaks.get(1).size());

输出是

expected size is 3: 1

改变它的

nobreaks.put(1, new HashSet(Arrays.asList( 2, 4, 5 )));

输出是

expected size is 3: 3
private Map<Integer, Set<Integer>> nobreaks = new HashMap();
nobreaks.put(1, new HashSet(Arrays.asList(new int[]{2, 4, 5})));
System.out.println("expected size is 3: " +nobreaks.get(1).size());

the output is

expected size is 3: 1

change it to

nobreaks.put(1, new HashSet(Arrays.asList( 2, 4, 5 )));

the output is

expected size is 3: 3
夏了南城 2024-09-13 05:40:49

对于任何解决 Android 问题的人:

Kotlin Collections 解决方案

星号 *spread 运算符。它单独应用集合中的所有元素,每个元素按顺序传递给 vararg 方法参数。它相当于:

val myArray = arrayOf("data", "foo")
val mySet = setOf(*myArray)

// Equivalent to
val mySet = setOf("data", "foo")

// Multiple spreads ["data", "foo", "bar", "data", "foo"]
val mySet = setOf(*myArray, "bar", *myArray)

不传递参数 setOf() 会导致空集。

除了 setOf 之外,您还可以将其中任何一个用于特定的哈希类型:

hashSetOf()
linkedSetOf()
mutableSetOf()
sortableSetOf()

这是显式定义集合项类型的方法。

setOf<String>()
hashSetOf<MyClass>()

For anyone solving for Android:

Kotlin Collections Solution

The asterisk * is the spread operator. It applies all elements in a collection individually, each passed in order to a vararg method parameter. It is equivalent to:

val myArray = arrayOf("data", "foo")
val mySet = setOf(*myArray)

// Equivalent to
val mySet = setOf("data", "foo")

// Multiple spreads ["data", "foo", "bar", "data", "foo"]
val mySet = setOf(*myArray, "bar", *myArray)

Passing no parameters setOf() results in an empty set.

In addition to setOf, you can also use any of these for a specific hash type:

hashSetOf()
linkedSetOf()
mutableSetOf()
sortableSetOf()

This is how to define the collection item type explicitly.

setOf<String>()
hashSetOf<MyClass>()
七堇年 2024-09-13 05:40:49

如果您需要构建一个仅包含一个元素的不可变集,可以使用Collections.singleton(...)。这是一个例子:

Set<String> mySet = Collections.singleton("Have a good day :-)");

这并没有回答原来的问题,但可能对某人有用(至少对我有用)。如果您认为这个答案不合适,请告诉我,我将删除它。

If you need to build an immutable set with only one element inside it, you can use Collections.singleton(...). Here is an example:

Set<String> mySet = Collections.singleton("Have a good day :-)");

This doesn't answer the original question but might be useful to someone (it would have been at least to me). If you think this answer does not fit just tell me and I will delete it.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文