Examples of Conversion Between Array and Set in Java

This tutorial illustrates examples to Convert an Array to a Set, as well as Convert a Set to an Array using Plain Java, Guava, and Apache Commons Collections API.

Set to Array Convertion

First, we will see examples of converting a Java Set to an Array.

Using Plain Java

We can use the toArray method on the Set to convert it to an Array.

Set<Integer> integerSet = Set.of(10, 20, 30); Integer[] integerArray = integerSet.toArray(new Integer[0]);
Code language: Java (java)

Although, by default the method returns an array of Object class, we can pass an empty Integer array to get the results in the form of array of Integers.

Using Guava Library

Alternatively, we can use Guava API to achieve the conversion.

Set<Integer> integerSet = Set.of(10, 20, 30); int[] integerArray = Ints.toArray(integerSet);
Code language: Java (java)

Array to Set Conversion

Now that we have seen a couple of ways to convert a Set to an Array, not we will do the other way.

Most importantly, Set is a collection of unique elements. Thus, when we convert an array with duplicate elements to Set, we find the duplicate elements are removed.

Using Plain Java

There are a few ways to convert an Array into Set. The most basic way is to use the factory methods of Set interface. However, the factory methods produce an Immutable Set instance.

Integer[] integerArray = new Integer[]{12, 20, 30}; Set<Integer> integerSet = Set.of(integerArray);
Code language: Java (java)

Alternatively, we can first convert Array to a List and use the list to create a HashSet. Remember, the Set we create using constructor is a mutable Set.

Integer[] integerArray = new Integer[]{12, 20, 30}; Set<Integer> integerSet = new HashSet<>(Arrays.asList(integerArray));
Code language: Java (java)

Finally, we can also create an empty set first and then populate it with array elements by using Collections.

Integer[] integerArray = new Integer[]{12, 20, 30}; Set<Integer> integerSet = new HashSet<>(); Collections.addAll(integerSet, integerArray);
Code language: Java (java)

Using Guava Library

The Guava Library provides Set which is a utility class. We can use Sets#newHashSet method to create a Set from an array.

Integer[] integerArray = new Integer[]{12, 20, 30}; Set<Integer> integerSet = Sets.newHashSet(integerArray);
Code language: Java (java)

Using Apache Commons Collections Library

Lastly, we will use Apache Commons Collections Library to convert an array to a Set.

Integer[] integerArray = new Integer[]{12, 20, 30}; Set<Integer> integerSet = new HashSet<>(); CollectionUtils.addAll(integerSet, integerArray);
Code language: Java (java)

Summary

In this short tutorial we studied various way of Converting an Array to a Set and Converting a Set to an Array. We covered examples using Plain Java, Guava Library, and Apache Commons Library. For more Java Tutorials, please visit Java Tutorials.