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.

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.

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.

Related posts:

Java Program to Check if a Point d lies Inside or Outside a Circle Defined by Points a, b, c in a Pl...
Java Program to Perform the Shaker Sort
Consumer trong Java 8
Java – Generate Random String
Spring 5 Testing with @EnabledIf Annotation
Java Program to Remove the Edges in a Given Cyclic Graph such that its Linear Extension can be Found
Java Program to Implement Pagoda
Java Program to Implement Max Heap
Removing all Nulls from a List in Java
Java Program to Implement the Hill Cypher
Spring Cloud – Adding Angular
Merging Two Maps with Java 8
Hướng dẫn sử dụng lớp Console trong java
Prevent Cross-Site Scripting (XSS) in a Spring Application
Flattening Nested Collections in Java
Interface trong Java 8 – Default method và Static method
Life Cycle of a Thread in Java
Java Program to Find Nearest Neighbor for Dynamic Data Set
Java Program to Create a Balanced Binary Tree of the Incoming Data
Hướng dẫn Java Design Pattern – Command
Java Program to Implement Double Ended Queue
String Initialization in Java
Java Program to Implement IdentityHashMap API
Hướng dẫn Java Design Pattern – Mediator
Java Program to Implement the linear congruential generator for Pseudo Random Number Generation
Java Program to Compute the Area of a Triangle Using Determinants
Toán tử instanceof trong java
Introduction to Spring Cloud Rest Client with Netflix Ribbon
Java Perform to a 2D FFT Inplace Given a Complex 2D Array
Guide to Spring 5 WebFlux
Java Program to Represent Graph Using Incidence Matrix
Java Program to Implement Warshall Algorithm