Core Java

Converting int Array to HashSet

Java is a versatile and powerful programming language used for a wide range of applications. Sometimes, you may need to convert an array of integers (int[]) into a HashSet, a data structure that stores unique elements without duplicates. This can be a useful operation when you want to remove duplicate values or perform set operations like union, intersection, or difference on your integer array. In this article, we will explore converting an int Array to a HashSet in Java, step by step.

1. What is a HashSet?

Before we dive into the conversion process, let’s briefly understand what a HashSet is.

A HashSet is part of the Java Collections Framework and is a class that implements the Set interface. It represents an unordered collection of elements where each element must be unique. This means that you cannot have duplicate elements in a HashSet. It provides constant-time performance for basic operations like adding, removing, and checking for the presence of elements.

2. Converting int[] to HashSet Using a Loop

First, you need to create an int[] array with the integer values you want to convert into a HashSet.

Then, you’ll need to create an empty HashSet that will store the unique elements from the int[] array.

In this loop, we iterate through the intArray, and for each element (num), we add it to the intHashSet. As a result, the intHashSet will contain only unique values from the original intArray, effectively removing duplicates.

import java.util.HashSet;

public class IntArrayToHashSet {
    public static void main(String[] args) {
        int[] intArray = {1, 2, 3, 4, 5, 2, 3};

        HashSet intHashSet = new HashSet();

        for (int num : intArray) {
            intHashSet.add(num);
        }

        // Printing the unique elements in the HashSet
        System.out.println("Unique elements in the HashSet: " + intHashSet);
    }
}

When you run this code, you’ll see that the HashSet only contains the unique elements from the intArray, effectively removing duplicates.

Fig. 1: Converting int[] to HashSet Using a Loop.
Fig. 1: Converting int[] to HashSet Using a Loop.

3. Using Java Streams

Java Streams provide a more concise and functional approach to converting an int[] to a HashSet. You can use the distinct() method to eliminate duplicates and then collect the elements into a HashSet. Here’s an example:

int[] intArray = {1, 2, 2, 3, 4, 4, 5};
HashSet set = Arrays.stream(intArray)
                             .boxed()
                             .collect(Collectors.toCollection(HashSet::new));

System.out.println(set); // Output: [1, 2, 3, 4, 5]

In this code, we use the Arrays.stream() method to create a stream of integers, and then use boxed() to convert int to Integer. Finally, we collect the distinct elements into a HashSet using Collectors.toCollection(). Note that the boxed() method is necessary because the Collectors.toCollection() method expects a stream of objects, not a stream of primitive integers.

Fig. 2: Converting int[] to HashSet Using Java Streams.
Fig. 2: Converting int[] to HashSet Using Java Streams.

4. Using Apache Commons Lang Library

Apache Commons Lang is a popular library that provides utility classes for common tasks. You can use the ArrayUtils class to convert an int[] to a HashSet.

4.1 Add Apache Commons Lang Dependency

Inside your POM file, locate the <dependencies> section. If it doesn’t exist, you can create it. To use Apache Commons Lang, add the following dependency:

        <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.13.0</version>
        </dependency>    

Make sure to replace <version> with the latest version of Apache Commons Lang available at the time of your project setup. You can find the latest version on the Apache Commons Lang website.

4.2 Code Example

Here’s an example:

import org.apache.commons.lang3.ArrayUtils;

int[] intArray = {1, 2, 2, 3, 4, 4, 5};
HashSet set = new HashSet(Arrays.asList(ArrayUtils.toObject(intArray)));

System.out.println(set); // Output: [1, 2, 3, 4, 5]

In this code, we use ArrayUtils.toObject() to convert the intArray to an Integer[], and then we convert it to a List. Finally, we pass the List to the HashSet constructor to obtain a HashSet containing unique elements.

Fig. 3: Converting int[] to HashSet Using Apache Commons Lang Library.
Fig. 3: Converting int[] to HashSet Using Apache Commons Lang Library.

5. Using Google Guava Library

Google Guava is another popular library that provides a convenient way to convert an int[] to a HashSet.

5.1 Add Google Guava Dependency

Inside your POM file, navigate to the <dependencies> section, or create it if it doesn’t exist. To use Google Guava, add the following dependency:

        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>32.1.2-jre</version>
        </dependency>    

Replace <version> with the latest version of Google Guava available at the time of your project setup. You can find the latest version on the Google Guava GitHub releases page.

5.2 Code Example

Here’s an example:

import com.google.common.collect.Sets;

HashSet set2 = Sets.newHashSet(Arrays.asList(ArrayUtils.toObject(intArray)));
System.out.println(set2); // Output: [1, 2, 3, 4, 5]

In this code, we use the Sets.newHashSet() method from Guava to create a HashSet directly from the intArray. Guava simplifies the process by providing dedicated utility methods for common tasks like this one.

Fig. 4: Converting int[] to HashSet Using Google Guava Library.
Fig. 4: Converting int[] to HashSet Using Google Guava Library.

6. Conclusion

Converting an int[] array to a HashSet in Java is a straightforward process that involves creating a HashSet, iterating through the array, and adding elements to the HashSet. This allows you to work with unique integer values and perform various set operations efficiently. Understanding how to perform this conversion can be valuable in scenarios where you need to handle collections of data with unique elements.

7. Download the Source Code

This was an example of how to convert an int Array to a HashSet!

Download
You can download the full source code of this example here: Java – Converting int Array to HashSet

Odysseas Mourtzoukos

Mourtzoukos Odysseas is studying to become a software engineer, at Harokopio University of Athens. Along with his studies, he is getting involved with different projects on gaming development and web applications. He is looking forward to sharing his knowledge and experience with the world.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button