Java HashSet

Java HashSet

Overview

Java HashSet class is a member of Java collections framework. HashSet implements Set interface and extends AbstractSet.

For official documentation on HashSet, please visit here

HashSet Class Hierarchy

Some of the key points of HashSet include :

  • HashSet cannot contain duplicate values.
  • HashSet is an unordered collection. It does not maintain the order in which the elements are inserted.
  • HashSet allows null value.
  • HashSet internally uses a HashMap to store its elements.
  • HashSet is not thread-safe. If multiple threads try to modify a HashSet at the same time, then the final outcome is not-deterministic. You must explicitly synchronize concurrent access to a HashSet in a multi-threaded environment.
  • HashSet also implements Searlizable and Cloneable interfaces.

HashSet Declaration

Here is the declaration for HashSet

public class HashSet<E> extends AbstractSet<E> implements Set<E>, Cloneable, Serializable  

HashSet Constructors

ConstructorDescription
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.Here the fill ratio must be between 0.0 and 1.0, and it determines how full the hash set can be before it is resized upward. Specifically, when the number of elements is greater than the capacity of the hash set multiplied by its fill ratio, the hash set is expanded.

Methods & Description

Apart from the methods inherited from its parent classes, HashSet defines following methods

MethodDescription
boolean add(Object o)Adds the specified element to this set if it is not already present.
void clear()Removes all of the elements from this set.
Object clone()Returns a shallow copy of this HashSet instance: the elements themselves are not cloned.
boolean contains(Object o)Returns true if this set contains the specified element.
boolean isEmpty()Returns true if this set contains no elements.
Iterator iterator()Returns an iterator over the elements in this set.
boolean remove(Object o)Removes the specified element from this set if it is present.
int size()Returns the number of elements in this set (its cardinality).

Creating a HashSet

The example below shows how to create a HashSet using the HashSet() constructor

import java.util.HashSet;
import java.util.Set;
public class CreateHashSetExample {
    public static void main(String[] args) {
        // Creating a HashSet
        Set<String> set1 = new HashSet<>();
        Set<String> set2 = new HashSet<>(set1);
        // creating a hashset with capacity
        Set<String> set3 = new HashSet<>(10);
        Set<String> set4 = new HashSet<>(5, 0.75);
    }
}

Adding elements to HashSet

Here is the example that shows how to add elements to HashSet

package com.techijournal.HashSet;

import java.util.HashSet;
import java.util.Set;

public class HashSetExample {
	public static void main(String[] args) {
		// Creating a HashSet
		Set<String> set1 = new HashSet<>();
		// Adding new elements to the HashSet
		set1.add("TechiJournal");
		set1.add("Callicoder");
		set1.add("GeeksForGeeks");
		set1.add("TutorialsPoint");
		set1.add("JavaTpoint");
		// Adding duplicate elements will be ignored
		set1.add("BeginnersBook");
		System.out.println(set1);
	}
}
Output : 
[Callicoder, TechiJournal, BeginnersBook, TutorialsPoint, GeeksForGeeks, JavaTpoint]

Creating a HashSet from another collection

The below example shows how to create a Set from other collection

package com.techijournal.HashSet;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class AddSet {

	public static void main(String[] args) {
		List<Integer> list1 = new ArrayList<>();
		list1.add(5);
		list1.add(10);
		list1.add(15);
		List<Integer> list2 = new ArrayList<>();
		list2.add(3);
		list2.add(6);
		list2.add(9);
		// Creating a HashSet from another collection (ArrayList)
		Set<Integer> set1 = new HashSet<>(list1);
		// Adding all the elements from an existing collection to a HashSet
		set1.addAll(list2);
		System.out.println(set1);
	}

}

Output : 
[3, 5, 6, 9, 10, 15]

Removing elements from a HashSet

Here is the example that shows :

  • Remove all the elements that exist in a given collection from the HashSet.
  • Remove an element from a HashSet.
  • Remove all the elements that satisfy a given predicate from the HashSet.
  • Clear the HashSet completely by removing all the elements.
package com.techijournal.HashSet;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class RemoveSet {
	public static void main(String[] args) {
		Set<String> set1 = new HashSet<>();
		set1.add("Sumanth");
		set1.add("Durgesh");
		set1.add("Lokesh");
		set1.add("Vamsi");
		set1.add("Deepthi");
		set1.add("Prasanth");
		System.out.println("names : " + set1);
		// Remove an element from a HashSet (The remove() method returns false if the
		// element does not exist in the HashSet)
		boolean isRemoved = set1.remove("Deepthi");
		System.out.println("After remove(Deepthi) => " + set1);

		// Remove all elements belonging to a given collection from a HashSet
		List<String> duplicateNames = new ArrayList<>();
		duplicateNames.add("Prasanth");
		duplicateNames.add("Riya");
		set1.removeAll(duplicateNames);
		System.out.println("After removeAll(perfectSquares) => " + set1);
		// Remove all elements matching a given predicate
		set1.removeIf(name -> name.equalsIgnoreCase("Prasanth"));
		System.out.println("After removeIf() => " + set1);
		// Remove all elements from HashSet (clear it completely)
		set1.clear();
		System.out.println("After clear() => " + set1);
	}
}

Output : 
names : [Durgesh, Vamsi, Sumanth, Prasanth, Lokesh, Deepthi]
After remove(Deepthi) => [Durgesh, Vamsi, Sumanth, Prasanth, Lokesh]
After removeAll(perfectSquares) => [Durgesh, Vamsi, Sumanth, Lokesh]
After removeIf() => [Durgesh, Vamsi, Sumanth, Lokesh]
After clear() => []

Iterating over HashSet

The following example shows different ways of iterating over a HashSet

package com.techijournal.HashSet;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

public class IterateHashSet {
	public static void main(String[] args) {
		Set<String> namesSet = new HashSet<>();
		namesSet.add("Sumanth");
		namesSet.add("Durgesh");
		namesSet.add("Vamsi");
		namesSet.add("Sneha");
		namesSet.add("Deepthi");
		namesSet.add("Sachin");
		System.out.println("=== Iterate over a HashSet using Java 8 forEach and lambda ===");
		namesSet.forEach(name -> {
			System.out.println(name);
		});
		System.out.println("=== Iterate over a HashSet using iterator() ===");
		Iterator<String> namesIterator = namesSet.iterator();
		while (namesIterator.hasNext()) {
			String name = namesIterator.next();
			System.out.println(name);
		}
		System.out.println("=== Iterate over a HashSet using iterator() and Java 8 forEachRemaining() method ===");
		namesIterator = namesSet.iterator();
		namesIterator.forEachRemaining(name -> {
			System.out.println(name);
		});
		System.out.println("=== Iterate over a HashSet using simple for-each loop ===");
		for (String name : namesSet) {
			System.out.println(name);
		}
	}
}

Output : 
=== Iterate over a HashSet using Java 8 forEach and lambda ===
Durgesh
Vamsi
Sumanth
Sneha
Deepthi
Sachin
=== Iterate over a HashSet using iterator() ===
Durgesh
Vamsi
Sumanth
Sneha
Deepthi
Sachin
=== Iterate over a HashSet using iterator() and Java 8 forEachRemaining() method ===
Durgesh
Vamsi
Sumanth
Sneha
Deepthi
Sachin
=== Iterate over a HashSet using simple for-each loop ===
Durgesh
Vamsi
Sumanth
Sneha
Deepthi
Sachin

Userdefined Objects in HashSet

This example shows how to create a HashSet of user defined objects.

package com.techijournal.HashSet;

import java.util.HashSet;
import java.util.Objects;
import java.util.Set;

class Movie {
	private long movieId;
	private String movieName;

	public Movie(long movieId, String movieName) {
		this.movieId = movieId;
		this.movieName = movieName;
	}

	public long getMovieId() {
		return movieId;
	}

	public void setMovieId(long movieId) {
		this.movieId = movieId;
	}

	public String getMovieName() {
		return movieName;
	}

	public void setMovieName(String movieName) {
		this.movieName = movieName;
	}

	@Override
	public boolean equals(Object o) {
		if (this == o)
			return true;
		if (o == null || getClass() != o.getClass())
			return false;
		Movie movie = (Movie) o;
		return movieId == movie.movieId;
	}

	@Override
	public int hashCode() {
		return Objects.hash(Long.valueOf(movieId));
	}

	@Override
	public String toString() {
		return "Movie{" + "id=" + movieId + ", name='" + movieName + '\'' + '}';
	}
}

public class HashSetUserDefined {
	public static void main(String[] args) {
		Set<Movie> movies = new HashSet<>();
		movies.add(new Movie(1, "Bahubali"));
		movies.add(new Movie(2, "Dangal"));
		movies.add(new Movie(3, "Ratsasan"));
		movies.add(new Movie(1, "Bahubali"));
		System.out.println(movies);
	}
}
Output : 
[Movie{id=1, name='Bahubali'}, Movie{id=2, name='Dangal'}, Movie{id=3, name='Ratsasan'}]

Conclusion

In this article, you learned about HashSet, its constructors and methods, how to add elements to a HashSet, how to remove elements from the HashSet, how to iterate over a HashSet, and how to create a HashSet of user defined objects.

Thanks, Note

Thanks for spending your valuable time reading this post. Hope this post taught you something new today. Please share the post if you like it.

Sumanth Patnaikuni

Hi Guys. I am a technology enthusiast always try to learn new things. So I decided to share my knowledge through this platform. I worked for several companies and having 4+ years of experience. as full stack developer. Please leave your comments if there is any doubt regarding the blog. And also please recommend me if you require any particular topic so that I can guide you through my blog.

Leave a Reply