在Java中在Array和Set之間進行轉換
1.概述
在這篇簡短的文章中,我們將研究在**數組和Set之間進行轉換**–首先使用純Java,然後使用Guava和Apache的Commons Collections庫。
本文是Baeldung上的“ Java – Back to Basic”系列的一部分。
2.將數組轉換為集合
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。使用谷歌番石榴
接下來,讓我們看一下番石榴從數組到Set的轉換:
@Test
public void givenUsingGuava_whenArrayConvertedToSet_thenCorrect() {
Integer[] sourceArray = { 0, 1, 2, 3, 4, 5 };
Set<Integer> targetSet = Sets.newHashSet(sourceArray);
}
2.3。使用Apache Commons集合
最後,讓我們使用Apache的Commons Collection庫進行轉換:
@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.將集合轉換為數組
3.1。使用純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 [size])相比, toArray(new T [0])是使用該方法的首選方法。正如AlekseyShipilëv在其博客文章中所證明的那樣,它看起來更快,更安全,更乾淨。
3.2。使用番石榴
下一步–番石榴解決方案:
@Test
public void givenUsingGuava_whenSetConvertedToArray_thenCorrect() {
Set<Integer> sourceSet = Sets.newHashSet(0, 1, 2, 3, 4, 5);
int[] targetArray = Ints.toArray(sourceSet);
}
請注意,我們使用的是Guava的Ints API,因此此解決方案特定於我們正在使用的數據類型。
4。結論
所有這些示例和代碼段的實現都可以在Github上找到-這是一個基於Maven的項目,因此應該很容易直接導入和運行。
0 條評論,你可以發表評論,我們會進行改進
