1. 概述

本文将探讨数组与Set之间的相互转换,分别使用原生Java、Google Guava和Apache Commons Collections三种实现方式。本文属于"Java基础回顾"系列的一部分。

2. 数组转Set

2.1. 使用原生Java

原生Java实现数组转Set有两种常见方式:

@Test
public void givenUsingCoreJavaV1_whenArrayConvertedToSet_thenCorrect() {
    Integer[] sourceArray = { 0, 1, 2, 3, 4, 5 };
    Set<Integer> targetSet = new HashSet<Integer>(Arrays.asList(sourceArray));
}

或者先创建Set再填充元素:

@Test
public void givenUsingCoreJavaV2_whenArrayConvertedToSet_thenCorrect() {
    Integer[] sourceArray = { 0, 1, 2, 3, 4, 5 };
    Set<Integer> targetSet = new HashSet<Integer>();
    Collections.addAll(targetSet, sourceArray);
}

2.2. 使用Google Guava

Guava的转换方式更为简洁:

@Test
public void givenUsingGuava_whenArrayConvertedToSet_thenCorrect() {
    Integer[] sourceArray = { 0, 1, 2, 3, 4, 5 };
    Set<Integer> targetSet = Sets.newHashSet(sourceArray);
}

2.3. 使用Apache Commons Collections

Commons Collections的实现需要预先指定Set容量:

@Test
public void givenUsingCommonsCollections_whenArrayConvertedToSet_thenCorrect() {
    Integer[] sourceArray = { 0, 1, 2, 3, 4, 5 };
    Set<Integer> targetSet = new HashSet<>(6);
    CollectionUtils.addAll(targetSet, sourceArray);
}

3. Set转数组

3.1. 使用原生Java

原生Java转换Set为数组的推荐方式:

@Test
public void givenUsingCoreJava_whenSetConvertedToArray_thenCorrect() {
    Set<Integer> sourceSet = Sets.newHashSet(0, 1, 2, 3, 4, 5);
    Integer[] targetArray = sourceSet.toArray(new Integer[0]);
}

⚠️ 注意:优先使用toArray(new T[0])而非toArray(new T[size]),根据Aleksey Shipilëv的性能分析,这种方式更高效、安全且简洁。

3.2. 使用Guava

Guava的特定类型转换(以int为例):

@Test
public void givenUsingGuava_whenSetConvertedToArray_thenCorrect() {
    Set<Integer> sourceSet = Sets.newHashSet(0, 1, 2, 3, 4, 5);
    int[] targetArray = Ints.toArray(sourceSet);
}

✅ 这种方式利用了Guava的Ints工具类,但仅适用于特定数据类型

4. 结论

本文展示了三种主流库实现数组与Set转换的方式:

  • 原生Java:无需依赖,适合简单场景
  • Guava:API简洁,但需注意类型限制
  • Commons Collections:功能全面,但稍显繁琐

所有示例代码可在GitHub项目中找到,这是一个Maven项目,可直接导入运行。


原始标题:Converting between an Array and a Set in Java | Baeldung