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

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

有什么想法吗?


当前回答

在Java 10中:

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

Set.copyOf返回包含给定集合元素的不可修改集合。

给定的集合不能为null,并且不能包含任何null元素。

其他回答

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。

“对类型、可变性、可序列化性或返回Set的线程安全性。"

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

不可变集(Java 9)

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

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

有关详细信息,请检查不可变设置静态工厂方法。

不可变集(Java 10)

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

Set.copyOf(Arrays.asList(array))Arrays.stream(array).collector(Collectors.toUnmodifiebleList());

Collectors.toUnmodifiebleList()方法在内部使用了Java9中引入的Set.of。还要查看我的答案以了解更多信息。

这样地:

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(例如…)

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

注意:我是Eclipse集合的提交人

我根据上面的建议写了下面的内容——偷吧……真不错!

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

在完成Arrays.asList(array)之后,可以执行Setset=newHashSet(list);

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

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