Skip to content

Java HashSet Tutorial with Examples

Java HashSet tutorial with examples will help you understand how to use HashSet class in an easy way. HashSet in Java is an implementation of the Set interface. The HashSet class is backed by an instance of the HashMap. Java Set is a collection that allows only unique values.

The HashSet in Java does not guarantee the order of the elements. That means that the elements may not be returned in the same order in which they were inserted into the HashSet.

Java HashSet Tutorial

The HashSet class allows a null element, but since it is a collection of unique values, only one null element can be inserted into the HashSet object.

The HashSet implementation is not synchronized. That means if multiple threads are trying to modify the HashSet object concurrently, the code must do synchronization explicitly. However, you can get the synchronized Set from the HashSet object using the synchronizedSet method of the Collections class as given below.

You can also use the existing HashSet object instead of creating a new one to get the synchronized Set object.

Since the HashSet class is backed by HashMap, it offers constant time performance for basic operations like add, remove, contains and size.

How to create an object of HashSet?

You can create an object of HashSet in Java using the HashSet constructors. The below given default no argument constructor creates a new and empty HashSet object.

If you want to create a new HashSet object from an existing Collection object, you can use the below given HashSet constructor.

This HashSet constructor creates an object of the HashSet containing the elements of the specified collection. The below given example shows how to convert ArrayList to HashSet object using this constructor.

Output

Note: As you can see from the output, the fourth “Red” element of the ArrayList is not included in the HashSet as it is duplicate of the first element.

HashSet Methods

Below given are some of the important methods of the HashSet class in Java.

How to add elements to HashSet using the add and addAll methods?

The add method of HashSet class is used to add an element to the HashSet. Since the HashSet class is an implementation of the Set which only accepts unique elements, the element will only be added to the HashSet if it does not already exist. The add method returns true if the element was added to the HashSet. It returns false if the element was not added to the Set because it was already present in the HashSet object.

Output

As you can see from the output, the “Green” element was not added to the HashSet because it was already present in the object.

How to add all elements of the specified Collection to the HashSet?

The addAll method of the HashSet class adds all the elements of the specified collection to this HashSet object. It returns true if the set is changed after the method call, false otherwise. The below given example shows how to add all elements of an ArrayList to the HashSet object.

Output

As you can see from the output, the element “Three” is not added to the HashSet from the ArrayList, as it already existed in the HashSet object.

How to remove elements from the HashSet using remove, removeAll and clear methods?

The HashSet remove method is used to remove an element from the HashSet object. The remove method returns true if the element was present in the HashSet and it was removed. If the element is not present in the HashSet, the remove method returns false.

Output

How to remove all elements of the HashSet which are contained in another collection?

The removeAll method removes all elements of the HashSet which are also contained in the specified collection. It returns true if the set object is changed as a result of this method call, false otherwise. The below given example shows how to remove all common elements between HashSet and ArrayList objects.

Output

How to remove all elements from HashSet using the clear method?

The HashSet clear method removes all elements from the HashSet object. The HashSet will be empty after you call the clear method on the HashSet object.

Output

How to get the size of the HashSet (HashSet length)?

The HashSet size method returns the number of elements contained in the HashSet object. It returns 0 if the HashSet is empty.

Output

You can also get the HashSet size using the size method and compare it with zero to check if the HashSet is empty instead of using the isEmpty method. However, the isEmpty method is recommended to check as it clearly stats the purpose of the code and easier to read approach.

How to check if the HashSet is empty using the isEmpty method?

The HashSet isEmpty method returns true if the HashSet object does not contain any elements. It returns false if there is at least one element in the HashSet object.

Output

How to check if the HashSet contains an element?

The HashSet contains method is used to check if the HashSet object contains the specified element. The contains method returns true if the element is found, false otherwise.

Output

Note: If the HashSet contains objects of the custom class, the class must implement the equals method for the contains method to work.

How to convert HashSet to an array using the toArray method?

The HashSet toArray method is used to convert the HashSet object to an array.

Output

If the size of the specified array is less than the size of the HashSet object, a new array is created. If the specified array is larger than the size of the HashSet, the array element immediately after the end of the HashSet elements is set to null.

It is recommended to pass the array of the same length to the toArray method to avoid the costly new array allocation operation. Please refer to the full example of how to convert HashSet to an array to know more.

How to iterate HashSet elements?

How to iterate over elements of the HashSet using the iterator?

The HashSet iterator method returns an Iterator object using which you can iterate over the elements of the HashSet (by using hashNext and next methods).

Output

How to iterate over elements of HashSet using the enhanced for loop?

You can iterate through the HashSet object using the enhanced for loop as given below.

Output

How to check if the HashSet contains all elements of another collection using the containsAll method?

The containsAll method returns true if this HashSet object contains all the elements contained in the specified collection object. It returns false otherwise.

Output

How to remove all elements of the HashSet which are not present in another collection using the retainAll method?

The retainAll method of the HashSet class removes all the elements from the HashSet object which are not present in the specified collection. In other words, all the elements which are common in both will be retained, other elements will be removed from this HashSet object.

Output

How to sort HashSet object?

The HashSet class does not guarantee the order of its elements as it is an unordered collection. If you want to sort the elements of the HashSet, you can convert HashSet to ArrayList and then sort the ArrayList using the sort method of the Collections class.

Output

However, the better approach would be to use the TreeSet instead of the HashSet class if you need the elements to be sorted by some order.

Output

How to clone HashSet in Java?

The clone method of the HashSet class returns a shallow copy of this HashSet object.  An important thing to remember is that the clone method does not deep clone the HashSet object. It copies the element references to the cloned HashSet object, not the actual objects, that is why it is called a shallow copy.

Refer to the below given HashSet clone example to understand how it works.

Output

Below given are the additional HashSet examples which cover the topics in more detail.

Java HashSet Examples

References:
Java HashSet Javadoc

Please let me know if you liked the Java HashSet tutorial with examples in the comments section below.

About the author

Leave a Reply

Your email address will not be published.