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 Implement Unrolled Linked List
Check if a String is a Palindrome in Java
Java Program to Find kth Smallest Element by the Method of Partitioning the Array
Java Program to Implement Ternary Search Algorithm
Removing all Nulls from a List in Java
Introduction to the Functional Web Framework in Spring 5
Hướng dẫn sử dụng Java Annotation
Giới thiệu SOAP UI và thực hiện test Web Service
Deploy a Spring Boot App to Azure
Hướng dẫn Java Design Pattern – Dependency Injection
Spring Boot - Apache Kafka
Java Program to Check whether Graph is a Bipartite using 2 Color Algorithm
Java Program to Find the Median of two Sorted Arrays using Binary Search Approach
Hướng dẫn kết nối cơ sở dữ liệu với Java JDBC
Java Program to Implement HashMap API
Understanding Memory Leaks in Java
XML Serialization and Deserialization with Jackson
Java Program to Perform LU Decomposition of any Matrix
Hướng dẫn Java Design Pattern – DAO
Java Program to Implement Bucket Sort
Java Program to Perform Insertion in a 2 Dimension K-D Tree
Java Program to Check whether Graph is Biconnected
Java Program to Implement Binary Tree
Spring Security Login Page with React
Encode/Decode to/from Base64
Tiêu chuẩn coding trong Java (Coding Standards)
Java Program to Generate Date Between Given Range
Hướng dẫn Java Design Pattern – Abstract Factory
Kiểu dữ liệu Ngày Giờ (Date Time) trong java
Java Program to Implement Binary Heap
Java Program to Implement Miller Rabin Primality Test Algorithm
Convert Character Array to String in Java