Introduction to HashSet Java
HashSet Java is a class used to create a collection that uses a hash table for storage. It inherits the AbstractSet class and implements the Set interface. HashSet stores the elements by using a mechanism called hashing. HashSet contains only unique elements. In this tutorial, we will learn about hashset java. We will learn how we can declare and initialize java hashsets along with various examples.
We will also cover how we can iterate over hashset java with and without iterators. At the same time, we will also discuss the difference between hashset and hashmap. Moreover, we will also covert a java hashset to an array as well. All in all, this tutorial will contain all the necessary information about the java hashset.
Getting started with HashSet Java
We already had discussed that Java HashSet class is used to create a collection that uses a hash table for storage. It inherits the AbstractSet class and implements the Set interface. HashSet stores the elements by using a mechanism called hashing. Some of the important points about hashset java are listed below:
- HashSet Java contains only unique elements.
- HashSet Java allows null values.
- HashSet Java class is non-synchronized.
- HashSet Java doesn't maintain the insertion order. For example, elements are inserted on the basis of their hashcode.
- HashSet Java is the best approach for search operations.
Now, we know the basic information about the java hashset. Let us know jump into it and explain each concept.
Hashset Java class hierarchy
We already discussed that HashSet class extends AbstractSet class that in turn implements the Set interface. The set interface inherits the Collection interface that in turn extends the Iterable interface. See the diagram below, which shows this hierarchy.
Now let us see how we can declare and initialize hashset in java.
Declaration of hashset Java
Now let us see the java syntax for declaring the hashset. But before declaring the Hashset, make sure that you had imported the required libraries. Java hashset is found in the following libraries.
import java.util.HashSet;
Once we imported the java HashSet, then we can declare it. See the simple syntax below for the declaration of java HashSet.
HashSet h = new HashSet();
The hash code is used as the index at which the data associated with the key is stored. The transformation of the key into its hash code is performed automatically. HashSet class in java provides many methods and constructors, some of which are listed below.
HashSet( )
: This constructor constructs a default HashSet.HashSet(Collection c)
: This constructor initializes the hash set by using the elements of the collection c.HashSet(int capacity)
: This constructor initializes the capacity of the hash set to the given integer value capacity. The capacity grows automatically as elements are added to the HashSet.HashSet(int capacity, float fillRatio)
: This constructor initializes both the capacity and the fill ratio (also called load capacity) of the hash set from its arguments.
Iniliazation of HashSet java using constructor
In this method, first, we create an array then convert it to a list, and then pass it to the HashSet constructor that accepts another collection. See the simple example below:
// Imported arrays
import java.util.Arrays;
// imported hashset java
import java.util.HashSet;
// imported java set
import java.util.Set;
// class
public class Main {
public static void main(String[] args){
// Creating array
Integer[] array = {1, 2, 3, 4, 5, 6,7};
// Set demonstration using HashSet java Constructor
Set<Integer> newSet = new HashSet<>(Arrays.asList(array));
// printing
System.out.println(newSet);
}
}
Output:
[1, 2, 3, 4, 5, 6, 7]
Initialization of Java HashSet using collections
Collections class consists of several methods that operate on collections. We will see two methods to initialize java HashSet using collections. The first method is using Collection.addAll()
which adds all the specified elements to the specified collection of the specified type. See the example below:
// Imported arrays
import java.util.Arrays;
// Importing collections
import java.util.Collections;
// imported hashset java
import java.util.HashSet;
// imported java set
import java.util.Set;
// class
public class Main {
public static void main(String[] args){
// Creating array
Integer[] array = {1, 2, 3, 4, 5, 6,7};
// initalizing hashset java using collections
Set<Integer> newSet = Collections.<Integer> emptySet();
Collections.addAll(newSet = new HashSet<Integer>(Arrays.asList(array)));
// printing
System.out.println(newSet);
}
}
Output:
[1, 2, 3, 4, 5, 6, 7]
Notice that we imported collections in order to use it in our java program. Now let us use another method Collections.unmodifiableSet()
which adds the elements and returns an unmodifiable view of the specified set. See the example below:
// Imported arrays
import java.util.Arrays;
// Importing collections
import java.util.Collections;
// imported hashset java
import java.util.HashSet;
// imported java set
import java.util.Set;
// class
public class Main {
public static void main(String[] args){
// Creating array
Integer[] array = {1,2, 2, 2, 3, 4, 5, 6,7};
// initalizing hashset java using collections.unmodifieableSet
Set<Integer> newSet = Collections.unmodifiableSet(new HashSet<Integer> (Arrays.asList(array)));
// printing
System.out.println(newSet);
}
}
Output:
[1, 2, 3, 4, 5, 6, 7]
Initialization of Java HashSet using add() method each time
This method is simple, we just have to create a set using java hashset method and then add the elements one by one using the add method. See the example below:
// imported hashset java
import java.util.HashSet;
// imported java set
import java.util.Set;
// class
public class Main {
public static void main(String[] args){
// Create a set using hashset java
Set<Integer> newSet = new HashSet<Integer>();
// Add some elements to the set
newSet.add(1);
newSet.add(2);
newSet.add(3);
newSet.add(4);
newSet.add(5);
newSet.add(6);
newSet.add(7);
// printing
System.out.println(newSet);
}
}
Output:
[1, 2, 3, 4, 5, 6, 7]
Duplicate elements in Java HashSet
We already discussed that Java HashSet contains unique elements that mean they cannot contains duplicate elements. But what will happen if we add duplicate elements to java HashSet, will we get an error or they will be ignored by Java. Let us take an example and see what happens when we add duplicate elements. See the example below:
// imported hashset java and arrays
import java.util.Arrays;
import java.util.HashSet;
// imported java set
import java.util.Set;
// class
public class Main {
public static void main(String[] args){
// duplicate elements
Integer arr[] = { 1, 1, 1, 1, 1, 1, 1};
// Set demonstration using HashSet Constructor
Set<Integer> newSet = new HashSet<>(Arrays.asList(arr));
// printing
System.out.println(newSet);
}
}
Output:
[1]
Notice that we get only one element because a HashSet can contain only unique elements, not duplicate ones. All the duplicate elements will be eliminated and only unique values will be left. Even if we use the add()
method to add new duplicate values, they will not be added. See the example below:
// imported hashset java
import java.util.HashSet;
// imported java set
import java.util.Set;
// class
public class Main {
public static void main(String[] args){
// creating hashset java
Set<Integer> newSet = new HashSet<Integer>();
// adding elements
newSet.add(1);
newSet.add(1);
newSet.add(1);
newSet.add(1);
newSet.add(1);
// printing
System.out.println(newSet);
}
}
Output:
[1]
Notice that it didn't add the duplicated values.
Removing elements from Java HashSet
Sometimes, we may want to remove the elements from java HashSet and in java, we can do that. The java remove() method helps us to remove the specified element from the HashSet. The remove method is found inside Java.util.HashSet
libraries which we have to import before using the remove method. See the example below which removes some elements from java HashSet.
// imported hashset java and arrays
import java.util.Arrays;
import java.util.HashSet;
// imported java set
import java.util.Set;
// class
public class Main {
public static void main(String[] args){
// duplicate elements
String arr[] = {"welcome", "to", "go", "linux", "cloud"};
// Set demonstration using HashSet Constructor
Set<String> newSet = new HashSet<>(Arrays.asList(arr));
// printing
System.out.println("Before removing:"+newSet);
// removing the elements
newSet.remove("welcome");
newSet.remove("to");
// print
System.out.println("After removing:"+newSet);
}
}
Output:
Before removing: [cloud, linux, go, to, welcome]
After removing: [cloud, linux, go]
Notice that we had successfully removed the specified elements from java HashSet using the remove method.
Iterating over Java HashSet
Sometimes we may want to iterate the java HashSet, and it is totally fine and allowed to iterate them in java. There are basically two different ways to iterate java hashset. In this section, we will see both of the ways along with taking different examples.
Example-1: Iterate without using iterator
In this method, we do not need to define an iterator on the HashSet. Instead, we can use a forEach loop. You can read more about for-each loop from the article Java for loops. The following program shows the traversal of HashSet using a forEach loop.
// imported hashset java and arrays
import java.util.Arrays;
import java.util.HashSet;
// imported java set
import java.util.Set;
// class
public class Main {
public static void main(String[] args){
Integer arr[] = { 1, 2, 3, 4,5,6,7 };
// Set demonstration using HashSet Constructor
Set<Integer> newSet = new HashSet<>(Arrays.asList(arr));
// for each loop
for (Integer element : newSet) {
System.out.print(element + " , ");
}
}
}
Output:
1 , 2 , 3 , 4 , 5 , 6 , 7 ,
Example-2: Iterate Java HashSet using iterator
The next approach of iterating java HashSet is using an iterator. Here, we will define an iterator for the HashSet class and then traverse through it. We will use java while loop to iterate. You can read more about while loop from the article on Java while loops. See the example below which iterates the java HashSet using the while loop.
// imported hashset java and arrays
import java.util.Arrays;
import java.util.HashSet;
// importing iterator
import java.util.Iterator;
// imported java set
import java.util.Set;
// class
public class Main {
public static void main(String[] args){
Integer arr[] = { 1, 2, 3, 4,5,6,7 };
// Set demonstration using HashSet Constructor
Set<Integer> newSet = new HashSet<>(Arrays.asList(arr));
// converting the hashset to iterator
Iterator<Integer> hashset = newSet.iterator();
// while loop to iterate
while(hashset.hasNext()){
System.out.print(hashset.next() + " , ");
}
}
}
Output:
1 , 2 , 3 , 4 , 5 , 6 , 7 ,
Notice that we converted out java HashSet to a new iterator and then iterated using a while loop to print out all the elements.
Converting HashSet to java array
An array in Java is a set of variables referenced by using a single variable name combined with an index number. Each item of an array is an element. All the elements in an array must be of the same type. You can read more about arrays from the article on java arrays. In this section, we will see how we can convert java HashSet to a java array. See the example below which converts HashSet to an array.
// imported hashset java and arrays
import java.util.Arrays;
import java.util.HashSet;
// imported java set
import java.util.Set;
// class
public class Main {
public static void main(String[] args){
Integer arr[] = { 4, 1, 3, 2,10,7,6 };
// Set demonstration using HashSet Constructor
Set<Integer> newSet = new HashSet<>(Arrays.asList(arr));
// declaring java array
Integer[] numArray = new Integer[newSet.size()];
// converting to an array
newSet.toArray(numArray);
// for each loop
for(Integer val : numArray){
// printing elements
System.out.print(val + " ");
}
}
}
Output:
1 2 3 4 6 7 10
Java HashSet Vs Java HashMap
Java HashMap is a hash table-based implementation of Java's Map interface. A Map is a collection of key-value pairs. It maps keys to values. HashMap is an unordered collection. It does not guarantee any specific order of the elements. The following lists show some of the differences between java HashSet and java hashmap.
- Java HashSet implements Set interface while java hashmap implements Map interface.
- Java HashSet stores objects of a particular type while java hashmap stores key-value pairs of data.
- Java HashSet does not allow duplicate values of objects while duplicate values are allowed in java hashmap but not duplicate keys.
- HashSet is slower when compared to HashMap.
- In java HashSet, new objects are added using the
Add ()
method while in java hashmap uses theput ()
method to add key-value pairs.
Methods of HashSet java class
Here are few methods that are associated with the Java HashSet class. See the table below:
Method | Modifier and Type | Description |
---|---|---|
clear () | void | It is used to remove all of the elements from the set. |
add() | boolean | It is used to add the specified element to this set if it is not already present. |
clone() | object | It is used to return a shallow copy of this HashSet instance: the elements themselves are not cloned. |
isEmpty() | boolean | It is used to return true if this set contains no elements. |
contains() | boolean | It is used to return true if this set contains the specified element. |
remove() | boolean | It is used to remove the specified element from this set if it is present. |
iterator() | Iterator | It is used to return an iterator over the elements in this set. |
size() | int | It is used to return the number of elements in the set. |
spliterator() | Spliterator | It is used to create a late-binding and fail-fast Spliterator over the elements in the set. |
Summary
HashSet Java is a class that extends AbstractSet and implements the Set interface in Java. It is a very useful tool that allows us to store unique items and access them in constant time. No duplicate values are stored. In this tutorial, we almost learn each and everything about the java HashSet. We learned how to declare HashSet and we also covered various ways to initialize java HashSet along with various examples.
At the same time, we also discussed how to iterate over java HashSet with and without using iterators. Moreover, we also learned how we can covert java HashSet to a java array. In a nutshell, this tutorial contains all the necessary information that you need to know in order to start working with HashSet Java.
Further Reading
HashSet java
Hashset java documentation
Hashmap in java