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.
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.
1 |
Set<String> synchronizedSet = Collections.synchronizedSet( new HashSet<String>() ); |
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.
1 |
HashSet<String> hSetColors = new HashSet<String>(); |
If you want to create a new HashSet object from an existing Collection object, you can use the below given HashSet constructor.
1 |
public HashSet(Collection<? extends E> collection) |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
List<String> listColors = new ArrayList<String>(); listColors.add("Red"); listColors.add("Green"); listColors.add("Blue"); listColors.add("Red"); /* * To convert ArrayList to HashSet use the * HashSet constructor which accepts the Collection object */ HashSet<String> hSet = new HashSet<String>(listColors); System.out.println("HashSet contains: "); System.out.println(hSet); |
Output
1 2 |
HashSet contains: [Red, Blue, Green] |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
HashSet<String> hSetColors = new HashSet<String>(); /* * Add elements to HashSet using add method */ hSetColors.add("Red"); hSetColors.add("Green"); hSetColors.add("Blue"); System.out.println("HashSet contains:"); System.out.println(hSetColors); /* * The add method returns true if element * was added to the HashSet. It returns false * if element was already present in the HashSet * and not added. */ if(hSetColors.add("Green")){ System.out.println("Element Green added to the Set"); }else{ System.out.println("Element green was not added, because it was already present"); } System.out.println("HashSet contains:"); System.out.println(hSetColors); |
Output
1 2 3 4 5 |
HashSet contains: [Red, Blue, Green] Element green was not added, because it was already present HashSet contains: [Red, Blue, Green] |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
HashSet<String> hSetNumbers = new HashSet<String>(); hSetNumbers.add("One"); hSetNumbers.add("Two"); hSetNumbers.add("Three"); List<String> listNumbers = new ArrayList<String>(); listNumbers.add("Three"); listNumbers.add("Four"); listNumbers.add("Five"); /* * To add all elements of a collection to the HashSet, use * the addAll method. */ hSetNumbers.addAll(listNumbers); System.out.println("HashSet contains: " + hSetNumbers); |
Output
1 |
HashSet contains: [Five, One, Four, Two, Three] |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
HashSet<String> hSetColors = new HashSet<String>(); hSetColors.add("Red"); hSetColors.add("Green"); hSetColors.add("Blue"); System.out.println("HashSet contains:"); System.out.println(hSetColors); /* * Use remove method to * remove an element from HashSet. */ boolean result = hSetColors.remove("Blue"); if(result){ System.out.println("Blue element was removed"); }else{ System.out.println("Blue element not found in the HashSet"); } result = hSetColors.remove("Yellow"); if(result){ System.out.println("Yellow element was removed"); }else{ System.out.println("Yellow element was not found in the HashSet"); } System.out.println("HashSet contains:"); System.out.println(hSetColors); |
Output
1 2 3 4 5 6 |
HashSet contains: [Red, Blue, Green] Blue element was removed Yellow element was not found in the HashSet HashSet contains: [Red, Green] |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
HashSet<String> hSetNumbers = new HashSet<String>(); hSetNumbers.add("One"); hSetNumbers.add("Two"); hSetNumbers.add("Three"); List<String> listNumbers = new ArrayList<String>(); listNumbers.add("Three"); listNumbers.add("Two"); listNumbers.add("Five"); /* * To remove common elements between HashSet and ArrayList, use * the removeAll method. */ //this will remove "Three" and "Two" from the HashSet object hSetNumbers.removeAll(listNumbers); System.out.println("HashSet contains: " + hSetNumbers); |
Output
1 |
HashSet contains: [One] |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
HashSet<String> hSetColors = new HashSet<String>(); hSetColors.add("Red"); hSetColors.add("Green"); hSetColors.add("Blue"); System.out.println("HashSet contains:"); System.out.println(hSetColors); /* * Use clear method to * remove all elements from HashSet. */ hSetColors.clear(); System.out.println("HashSet contains:"); System.out.println(hSetColors); |
Output
1 2 3 4 |
HashSet contains: [Red, Blue, Green] HashSet contains: [] |
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.
1 2 3 4 5 6 7 |
HashSet<String> hSetColors = new HashSet<String>(); hSetColors.add("Red"); hSetColors.add("Green"); hSetColors.add("Blue"); System.out.println("HashSet size:"); System.out.println(hSetColors.size()); |
Output
1 2 |
HashSet size: 3 |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
HashSet<String> hSetColors = new HashSet<String>(); hSetColors.add("Red"); hSetColors.add("Green"); hSetColors.add("Blue"); System.out.println("Is HashSet empty:"); System.out.println(hSetColors.isEmpty()); //remove all elements from HashSet hSetColors.clear(); System.out.println("Is HashSet empty:"); System.out.println(hSetColors.isEmpty()); |
Output
1 2 3 4 |
Is HashSet empty: false Is HashSet empty: true |
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.
1 2 3 4 5 6 7 8 9 10 |
HashSet<String> hSetColors = new HashSet<String>(); hSetColors.add("Red"); hSetColors.add("Green"); hSetColors.add("Blue"); boolean found = hSetColors.contains("Red"); System.out.println("HashSet contains Red: " + found); found = hSetColors.contains("Yellow"); System.out.println("HashSet contains Yellow: " + found); |
Output
1 2 |
HashSet contains Red: true HashSet contains Yellow: false |
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.
1 2 3 4 5 6 7 8 9 |
HashSet<String> hSetColors = new HashSet<String>(); hSetColors.add("Red"); hSetColors.add("Green"); hSetColors.add("Blue"); String[] strColorArray = hSetColors.toArray( new String[hSetColors.size()] ); System.out.println("Convert HashSet to array: "); System.out.println( Arrays.toString(strColorArray) ); |
Output
1 2 |
Convert HashSet to array: [Red, Blue, Green] |
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).
1 2 3 4 5 6 7 8 9 10 11 12 |
HashSet<String> hSetColors = new HashSet<String>(); hSetColors.add("Red"); hSetColors.add("Green"); hSetColors.add("Blue"); System.out.println("Iterating HashSet elements using the iterator"); //get an Iterator Iterator<String> iterator = hSetColors.iterator(); while(iterator.hasNext()){ System.out.println( iterator.next() ); } |
Output
1 2 3 4 |
Iterating HashSet elements using the iterator Red Blue Green |
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.
1 2 3 4 5 6 7 8 9 10 11 |
HashSet<String> hSetNumbers = new HashSet<String>(); hSetNumbers.add("One"); hSetNumbers.add("Two"); hSetNumbers.add("Three"); System.out.println("Iterating HashSet using the enhanced for loop"); //iterate through HashSet elements using the for loop for(String strElement : hSetNumbers){ System.out.println(strElement); } |
Output
1 2 3 4 |
Iterating HashSet using the enhanced for loop One Two Three |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
HashSet<String> hSetNumbers = new HashSet<String>(); hSetNumbers.add("One"); hSetNumbers.add("Two"); hSetNumbers.add("Three"); List<String> listNumbers = new ArrayList<String>(); listNumbers.add("One"); listNumbers.add("Two"); listNumbers.add("Three"); /* * To check if the HashSet contains all the elements of * another collection, use the containsAll method. */ //this will return true as the HashSet contains all elements of the ArrayList System.out.println( hSetNumbers.containsAll(listNumbers) ); //remove an element from the HashSet hSetNumbers.remove("Three"); /* * this will return false because the * HashSet does not contain all elements of the ArrayList * (Three is missing) */ System.out.println( hSetNumbers.containsAll(listNumbers) ); |
Output
1 2 |
true false |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
HashSet<String> hSetNumbers = new HashSet<String>(); hSetNumbers.add("One"); hSetNumbers.add("Two"); hSetNumbers.add("Three"); List<String> listNumbers = new ArrayList<String>(); listNumbers.add("One"); listNumbers.add("Two"); listNumbers.add("Four"); /* * To remove all HashSet elements which are not present in the * specified another collection, use the retainAll method */ /* * this will remove "Three" from the HashSet as it is * not contained in the ArrayList */ hSetNumbers.retainAll(listNumbers); System.out.println("HashSet contains: " + hSetNumbers); |
Output
1 |
HashSet contains: [One, Two] |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
HashSet<String> hSetLetters = new HashSet<String>(); hSetLetters.add("E"); hSetLetters.add("C"); hSetLetters.add("B"); hSetLetters.add("A"); hSetLetters.add("D"); /* * Convert Set to List and then sort the List * using the sort method of the Collections class */ List<String> sortedList = new ArrayList<String>( hSetLetters ); Collections.sort( sortedList ); System.out.println("Sorted list contains: " + sortedList); |
Output
1 |
Sorted list contains: [A, B, C, D, E] |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
HashSet<String> hSetLetters = new HashSet<String>(); hSetLetters.add("E"); hSetLetters.add("C"); hSetLetters.add("B"); hSetLetters.add("A"); hSetLetters.add("D"); /* * Create TreeSet from HashSet to automatically * sort the objects */ TreeSet<String> tSetLetters = new TreeSet(hSetLetters); System.out.println("TreeSet elements: " + tSetLetters); |
Output
1 |
TreeSet elements: [A, B, C, D, E] |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 |
class Car{ private String carBrand; private String carName; public Car(String carBrand, String carName){ this.carBrand = carBrand; this.carName = carName; } public String getCarBrand() { return carBrand; } public void setCarBrand(String carBrand) { this.carBrand = carBrand; } public String getCarName() { return carName; } public void setCarName(String carName) { this.carName = carName; } //to print the object public String toString(){ return "[" + getCarBrand() + ", " + getCarName() + "]"; } } public class Example { public static void main(String[] args){ Car car1 = new Car("Audi", "A8"); Car car2 = new Car("Suzuki", "Alto"); Car car3 = new Car("BMW", "X5"); HashSet<Car> hSetCars = new HashSet<Car>(); hSetCars.add( car1 ); hSetCars.add( car2 ); hSetCars.add( car3 ); /* * To clone HashSet object, use the clone method. */ HashSet<Car> hSetClonedCars = (HashSet<Car>)hSetCars.clone(); System.out.println("Original HashSet: " + hSetCars); System.out.println("Cloned HashSet: " + hSetClonedCars); /* * Adding or removing elements to either of the HashSet objects * does not affect the other */ //add new object to the original HashSet hSetCars.add( new Car("Skoda", "Laura") ); System.out.println("Original HashSet: " + hSetCars); System.out.println("Cloned HashSet: " + hSetClonedCars); /* * However, if you change the element object, the change * will be reflected in both the HashSet objects. */ //change an object, this will be changed in both the HashSet objects car1.setCarName("Breeza"); System.out.println("Original HashSet: " + hSetCars); System.out.println("Cloned HashSet: " + hSetClonedCars); } } |
Output
1 2 3 4 5 6 |
Original HashSet: [[BMW, X5], [Audi, A8], [Suzuki, Alto]] Cloned HashSet: [[BMW, X5], [Audi, A8], [Suzuki, Alto]] Original HashSet: [[BMW, X5], [Audi, A8], [Suzuki, Alto], [Skoda, Laura]] Cloned HashSet: [[BMW, X5], [Audi, A8], [Suzuki, Alto]] Original HashSet: [[BMW, X5], [Audi, Breeza], [Suzuki, Alto], [Skoda, Laura]] Cloned HashSet: [[BMW, X5], [Audi, Breeza], [Suzuki, Alto]] |
Below given are the additional HashSet examples which cover the topics in more detail.
Java HashSet Examples
- How to create new HashSet objects using HashSet constructor
- How to add elements to Java HashSet (add, addAll method)
- How to print Java HashSet elements
- How to sort Java HashSet elements
- How to check HashSet size (size method)
- How to check if HashSet is emtpy (isEmpty method)
- How to iterate HashSet in Java
- How to find the minimum or maximum value from Java HashSet
- How to get first or last elements from Java HashSet
- How to check if element exists in Java HashSet
- How to get random elements from Java HashSet
- How to remove elements from HashSet
- How to clear or remove all elements from HashSet
- How to get elements by index from HashSet in Java
- How to compare two HashSet objects using the equals method
- How to copy HashSet or append HashSet to another HashSet
- How to preserve insertion order of Java HashSet elements
- How to convert Java HashSet to comma separated string
- How to convert comma separated string to Java HashSet
- How to convert HashSet to ArrayList
- How to convert ArrayList to HashSet
- Convert HashSet to array
- Convert array to HashSet
- Convert List to HashSet
References:
Java HashSet Javadoc
Please let me know if you liked the Java HashSet tutorial with examples in the comments section below.