Convert Array to HashSet in Java
Last Updated :
09 Jan, 2023
The Single Data structure cannot be able to fulfill the requirements of the programmers that's why there are a lot of inbuilt Data-Structures in Programming languages.
Arrays are the most commonly used Data-Structure in most programming languages. The advantage of this Data-Structure is O(1) accessing the elements of the Arrays with the help of indexing but the most common disadvantages are we cannot change the size of the array after creating and the deletion of the elements is a complicated process in Arrays.
Sets: In Java, Any group of individual objects which are represented as a single unit is known as the collection of the objects. In Java, a separate framework named the “Collection Framework” has been defined in JDK 1.2 which holds all the collection classes and interface. Sets are classified into two parts sorted set and unsorted set both have advantage and disadvantage. Sorted Set i.e TreeSet sort its unique elements but the time-complexity of TreeSet is O(N log N) but unsorted Sets such as HashSet and LinkedSet do change the order of the elements but the difference between the HashSet and LinkedSet is Random Order of its elements.

Examples:
Input : Array: [1, 2, 3, 4, 5, 6]
Output: Set: [1, 2, 3, 4, 5, 6]
Input : Array: [a, b, c, d]
Output: Set: [a, b, c, d]
Approach: Brute Force or Naive Method
Create an empty set (HashSet if unsorted elements require) Iterate the elements of the array and add one by one to the set.
Example:
Java
// Convert array to HashSet in Java
import java.io.*;
import java.util.Iterator;
// Importing Set libraries
import java.util.Set;
import java.util.HashSet;
class GFG {
// Function to convert array to set
static Set<Integer> convert(int[] array)
{
// Hash Set Initialisation
Set<Integer> Set = new HashSet<>();
// Iteration using enhanced for loop
for (int element : array) {
Set.add(element);
}
// returning the set
return Set;
}
// Function to print the set
static void print(Set<Integer> Set)
{
// Implement to iterator the Set
Iterator<Integer> _iterator = Set.iterator();
// Iterate the elements of Set
while (_iterator.hasNext()) {
// print the element of the Set
System.out.print(_iterator.next() + " ");
}
}
public static void main(String[] args)
{
// Array taken for consideration
int array[] = { 1, 2, 3, 4, 5, 6 };
// Calling function to convert the array
Set<Integer> Set = convert(array);
// print the set
print(Set);
}
}
Approach 2:
Using Java 8 Stream API: HashSet constructor can take another collection object to construct a new set containing the elements of the specified array.
- Get the Array to be converted.
- Convert the array to Stream
- Convert the Stream to Set using Collectors.toSet()
- Collect the formed set using the collect() method
- Return the formed Set.
Example:
Java
// Convert Array to HashSet in Java
import java.util.*;
import java.util.stream.*;
class GFG {
// Generic function to convert array to set
public static <T> Set<T> convertArrayToSet(T array[])
{
// create a set from the Array
return Arrays.stream(array).collect(
Collectors.toSet());
}
public static void main(String args[])
{
// Create an Array
String array[]
= { "Geeks", "forGeeks", "A computer Portal" };
// Print the Array
System.out.println("Array: "
+ Arrays.toString(array));
// convert the Array to Set
Set<String> set = convertArrayToSet(array);
// Print the Set
System.out.println("Set: " + set);
}
}
OutputArray: [Geeks, forGeeks, A computer Portal]
Set: [A computer Portal, Geeks, forGeeks]
Similar Reads
Java Tutorial Java is a high-level, object-oriented programming language used to build web apps, mobile applications, and enterprise software systems. It is known for its Write Once, Run Anywhere capability, which means code written in Java can run on any device that supports the Java Virtual Machine (JVM).Java s
10 min read
Java OOP(Object Oriented Programming) Concepts Java Object-Oriented Programming (OOPs) is a fundamental concept in Java that every developer must understand. It allows developers to structure code using classes and objects, making it more modular, reusable, and scalable.The core idea of OOPs is to bind data and the functions that operate on it,
13 min read
Java Interview Questions and Answers Java is one of the most popular programming languages in the world, known for its versatility, portability, and wide range of applications. Java is the most used language in top companies such as Uber, Airbnb, Google, Netflix, Instagram, Spotify, Amazon, and many more because of its features and per
15+ min read
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Arrays in Java Arrays in Java are one of the most fundamental data structures that allow us to store multiple values of the same type in a single variable. They are useful for storing and managing collections of data. Arrays in Java are objects, which makes them work differently from arrays in C/C++ in terms of me
15+ min read
Collections in Java Any group of individual objects that are represented as a single unit is known as a Java Collection of Objects. In Java, a separate framework named the "Collection Framework" has been defined in JDK 1.2 which holds all the Java Collection Classes and Interface in it. In Java, the Collection interfac
15+ min read
Inheritance in Java Java Inheritance is a fundamental concept in OOP(Object-Oriented Programming). It is the mechanism in Java by which one class is allowed to inherit the features(fields and methods) of another class. In Java, Inheritance means creating new classes based on existing ones. A class that inherits from an
13 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Java Exception Handling Exception handling in Java allows developers to manage runtime errors effectively by using mechanisms like try-catch block, finally block, throwing Exceptions, Custom Exception handling, etc. An Exception is an unwanted or unexpected event that occurs during the execution of a program, i.e., at runt
10 min read
Java Programs - Java Programming Examples In this article, we will learn and prepare for Interviews using Java Programming Examples. From basic Java programs like the Fibonacci series, Prime numbers, Factorial numbers, and Palindrome numbers to advanced Java programs.Java is one of the most popular programming languages today because of its
8 min read