# 在Java中在Array和Set之間進行轉換

## 2.將數組轉換為集合

### 2.1。使用純Java

``````@Test

public void givenUsingCoreJavaV1_whenArrayConvertedToSet_thenCorrect() {

Integer[] sourceArray = { 0, 1, 2, 3, 4, 5 };

Set<Integer> targetSet = new HashSet<Integer>(Arrays.asList(sourceArray));

}``````

``````@Test

public void givenUsingCoreJavaV2_whenArrayConvertedToSet_thenCorrect() {

Integer[] sourceArray = { 0, 1, 2, 3, 4, 5 };

Set<Integer> targetSet = new HashSet<Integer>();

}``````

### 2.2。使用谷歌番石榴

``````@Test

public void givenUsingGuava_whenArrayConvertedToSet_thenCorrect() {

Integer[] sourceArray = { 0, 1, 2, 3, 4, 5 };

Set<Integer> targetSet = Sets.newHashSet(sourceArray);

}``````

### 2.3。使用Apache Commons集合

``````@Test

public void givenUsingCommonsCollections_whenArrayConvertedToSet_thenCorrect() {

Integer[] sourceArray = { 0, 1, 2, 3, 4, 5 };

Set<Integer> targetSet = new HashSet<>(6);

}``````

## 3.將集合轉換為數組

### 3.1。使用純Java

``````@Test

public void givenUsingCoreJava_whenSetConvertedToArray_thenCorrect() {

Set<Integer> sourceSet = Sets.newHashSet(0, 1, 2, 3, 4, 5);

Integer[] targetArray = sourceSet.toArray(new Integer[0]);

}``````

### 3.2。使用番石榴

``````@Test

public void givenUsingGuava_whenSetConvertedToArray_thenCorrect() {

Set<Integer> sourceSet = Sets.newHashSet(0, 1, 2, 3, 4, 5);

int[] targetArray = Ints.toArray(sourceSet);

}``````

## 4。結論

0 條評論，你可以發表評論，我們會進行改進