如何在Java中将数组转换为Set

本文翻译自:How to convert an Array to a Set in Java

I would like to convert an array to a Set in Java. 我想将数组转换为Java中的Set。 There are some obvious ways of doing this (ie with a loop) but I would like something a bit neater, something like: 有一些明显的方法可以做到这一点(即使用循环),但我想要一些更整洁的东西,如:

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

Any ideas? 有任何想法吗?


#1楼

参考:https://stackoom.com/question/CrCB/如何在Java中将数组转换为Set


#2楼

In Eclipse Collections , the following will work: Eclipse集合中 ,以下内容将起作用:

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的提交者


#3楼

Java 8: 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]

#4楼

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

#5楼

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

#6楼

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); }         
  • 7
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值