1. Overview
In this short article weβre going to look at converting between an array and a Set β first using plain java, then Guava and the Commons Collections library from Apache.
This article is part of the βJava β Back to Basicβ series here on Baeldung.
2. Convert Array to a Set
2.1. Using Plain Java
Letβs first look at how to turn the array to a Set using plain Java:
@Test
public void givenUsingCoreJavaV1_whenArrayConvertedToSet_thenCorrect() {
Integer[] sourceArray = { 0, 1, 2, 3, 4, 5 };
Set<Integer> targetSet = new HashSet<Integer>(Arrays.asList(sourceArray));
}
Alternatively, the Set can be created first and then filled with the array elements:
@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. Using Google Guava
Next, letβs look at the Guava conversion from array to Set:
@Test
public void givenUsingGuava_whenArrayConvertedToSet_thenCorrect() {
Integer[] sourceArray = { 0, 1, 2, 3, 4, 5 };
Set<Integer> targetSet = Sets.newHashSet(sourceArray);
}
2.3. Using Apache Commons Collections
Finally, letβs do the conversion using the Commons Collection library from Apache:
@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. Convert Set to Array
3.1. Using Plain Java
Now letβs look at the reverse β converting an existing Set to an array:
@Test
public void givenUsingCoreJava_whenSetConvertedToArray_thenCorrect() {
Set<Integer> sourceSet = Sets.newHashSet(0, 1, 2, 3, 4, 5);
Integer[] targetArray = sourceSet.toArray(new Integer[0]);
}
Note, that toArray(new T[0]) is the preferred way to use the method over the toArray(new T[size]). As Aleksey ShipilΓ«v proves in his blog post, it seems faster, safer, and cleaner.
3.2. Using Guava
Next β the Guava solution:
@Test
public void givenUsingGuava_whenSetConvertedToArray_thenCorrect() {
Set<Integer> sourceSet = Sets.newHashSet(0, 1, 2, 3, 4, 5);
int[] targetArray = Ints.toArray(sourceSet);
}
Notice that weβre using the Ints API from Guava, so this solution is specific to the data type that weβre working with.
