convert-array-to-set-and-set-to-array
Converting Between an Array and a Set in Java
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
@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
@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
@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
@Test
public void givenUsingCoreJava_whenSetConvertedToArray_thenCorrect() {
Set<Integer> sourceSet = Sets.newHashSet(0, 1, 2, 3, 4, 5);
Integer[] targetArray = sourceSet.toArray(new Integer[sourceSet.size()]);
}
3.2. Using Guava
@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.
3.3 Using Commons Collections
@Test
public void givenUsingCommonsCollections_whenSetConvertedToArray_thenCorrect() {
Set<Integer> sourceSet = Sets.newHashSet(0, 1, 2, 3, 4, 5);
Integer[] targetArray = sourceSet.toArray(new Integer[sourceSet.size()]);
}
4. Conclusion
The implementation of all these examples and code snippets can be found over on Github – this is a Maven-based project, so it should be easy to import and run as it is.