Java/J2EE and SOA (349 Blogs) Become a Certified Professional
AWS Global Infrastructure

Programming & Frameworks

Topics Covered
  • C Programming and Data Structures (16 Blogs)
  • Comprehensive Java Course (5 Blogs)
  • Java/J2EE and SOA (346 Blogs)
  • Spring Framework (8 Blogs)
SEE MORE

Learn what is HashSet in Java and how to get started with it!

Last updated on Jun 14,2021 7.2K Views

Swatee Chand
Sr Research Analyst at Edureka. A techno freak who likes to explore... Sr Research Analyst at Edureka. A techno freak who likes to explore different technologies. Likes to follow the technology trends in market and write...

HashSet in Java is one of the most important aspects of Java Collection hierarchy. It is typically used to store unique values in an unordered manner. Through the medium of this article on HashSet in Java, I will be giving you a complete walkthrough of what exactly is a HashSet and how you can use it in your application.

Below are the topics covered in this article:

Let’s get started by first understanding what are HashSet in Java.

HashSet in Java

java.util.HashSet class is a member of the Java collections framework which inherits the AbstractSet class and implements the Set interface. It implicitly implements a hashtable for creating and storing a collection of unique elements. Hashtable is nothing but an instance of the HashMap class that uses a hashing mechanism for storing the information within a HashSet.

Hashing is the process of converting the informational content into a unique value that is more popularly known as hash code. This hashcode is then used for indexing the data associated with the key. The entire process of transforming the informational key into the hashcode is performed internally.

Now for a better understanding of HashSet in Java, let me list down a few of its features:

  1. A HashSet in Java does not allow duplicate values.
  2. It can contain null values.
  3. HashSet doesn’t follow the insertion order for storing the data rather it makes use of the hashcode for indexing the values within.
  4. It is non-synchronized which automatically makes it thread-unsafe.
  5. HashSet class also implements Cloneable and Serializable interfaces.

Now that you are aware of what exactly is HashSet in Java, let’s move further with this article and demystify the differences between HashMap and HashSet in Java.

Java HashSet vs HashMap

HashSetHashMap
Implements java.util.Set interfaceImplements java.util.Map
Stores data as objectsStores data in the form of key-value pair
HashSet requires just one parameter for its object initializationIt requires two parameters (key, value) for its object initialization
Doesn’t allow duplicate elementsDoesn’t allow duplicate keys but you can store duplicate values
Allows a single null valueAllows a single null key and any number of null values
HashSet use add() method for add or storing dataHashMap use put() method for storing data

Now that you have a clear distinction between HashMap and HashSet, let’s now focus on HashSet again and dive deeper into it. In the next section of this article, I will be introducing you to the complete hierarchy of HashSet in Java.

HashSet Hierarchy in Java

As you can see from the below-given diagram, The HashSet class implements the Set interface. The Set interface further inherits the Collection interface which eventually extends the Iterable interface in a hierarchical order.

Java HashSet Hierarchy - HashSet in Java - Edureka

Now, moving ahead with this HashSet in Java article, let’s us check out the various constructors supported by this class.

Constructors of java.util.HashSet Class

ConstructorDescription
HashSet ()This is the default constructor of HashSet class
HashSet (int capacity)This constructor is used to initialize the initial capacity of the hash set. The capacity can grow dynamically with the addition of new elements
HashSet (int capacity, float loadCapacity)This constructor is used to initialize the initial capacity of the hash set along with the load capacity
HashSet (Collection c)This constructor is used to initialize the hash set by using the elements from Collection c

These were the four constructors of the HashSet class in Java. Let’s now find out what are the various methods defined in Java HashSet.

Methods of java.util.HashSet Class

MethodDescription
boolean add(Object obj)This method helps in adding a specified element into the HashSet only if it is not present
void clear()This method helps in removing all of the elements from HashSet
Object clone()This method returns a shallow copy of the HashSet instance rather than clones of the HashSet elements
boolean contains(Object o)This method returns true if the passed element is present within the HashSet
boolean isEmpty()This method returns true in case the HashSet is empty
Iterator iterator()This method returns an iterator over the elements present in the HashSet
boolean remove(Object o)This method helps in removing the specified element from the HashSet if it is present
int size()This method returns the total number of elements present in the HashSet

Along with the above-listed methods, the HashSet class in Java also contains the methods inherited from its superclasses.

Let’s now try implementing these methods and get our feet wet with coding.

Implementing HashSet in Java Program

In the below example, we will try and implement a number of methods provided by the HashSet class.

import java.util.HashSet;
import java.util.*;

public class SampleHashSet {
    public static void main(String[] args) {
        // Creating a HashSet
        Set<String> eduCourses = new HashSet<>();

        // Adding new elements to the HashSet
        eduCourses.add("Big Data");
        eduCourses.add("Node.js");
        eduCourses.add("Java");
        eduCourses.add("Python");
        eduCourses.add("Blockchain");
        eduCourses.add("JavaScript");
        eduCourses.add("Selenium");
        eduCourses.add("AWS");
        eduCourses.add("Machine Learning");
        eduCourses.add("RPA");
        

        // Adding duplicate elements will be ignored
        eduCourses.add("Java");
        eduCourses.add("RPA");

        System.out.println(eduCourses);
        
        // Check if the HashSet contains an specific element
        String myCourse = "Node.js";
        if(eduCourses.contains(myCourse)) {
            System.out.println(myCourse + " is in the courses list.");
        } else {
            System.out.println(myCourse + " is not in the courses list.");
        }
        
        // Sorting eduCourses using List 
        List<String> list = new ArrayList<String>(eduCourses); 
        Collections.sort(list); 
  
        // Printing the sorted elements of the HashSet 
        System.out.println("Printing the Courses in sorted order using List: " + list);
        
       // Removing items from HashSet using remove() 
        eduCourses.remove("Python"); 
          
        // Iterating over HashSet items 
        System.out.println("Iterating over course list after removing Python:"); 
        Iterator<String> i = eduCourses.iterator(); 
        while (i.hasNext()) 
            System.out.println(i.next()); 
        
        
        // Creating another object of HashSet 
        HashSet<String> eduNewCourses = new HashSet<String>(); 
        eduNewCourses.add("Node.js"); 
        eduNewCourses.add("Python");
        eduNewCourses.add("Machine Learning");
                    
        //Removing all the new elements from HashSet  
        eduCourses.removeAll(eduNewCourses);  
        System.out.println("After invoking removeAll() method courses left: "+ eduCourses); 
        
        //Removing elements on the basis of specified condition  
        eduCourses.removeIf(str->str.contains("Java"));    
        System.out.println("After invoking removeIf() method: "+ eduCourses);  
        
        // Removing elements from eduCourses which are specified in eduNewCourses 
        eduCourses.retainAll(eduNewCourses);
        System.out.println("HashSet after " + "retainAll() operation : " + eduNewCourses); 
        
        //Removing all the elements available in the set   
        eduCourses.clear();  
        System.out.println("After invoking clear() method: "+ eduCourses); 
       
    }
}

When you execute the above code, it will give you the below-shown output.

HashSet Output - HashSet in Java - Edureka

With this, we come to the end of this article. Hope I was able to keep the concepts crisp and clear. You can learn more about Java Collections by going through our other Java blogs.

Now that you have understood what is a HashSet in Java, check out the Java Certification Training by Edureka, a trusted online learning company with a network of more than 250,000 satisfied learners spread across the globe. Edureka’s Java J2EE and SOA training and certification course is designed for students and professionals who want to be a Java Developer. The course is designed to give you a head start into Java programming and train you for both core and advanced Java concepts along with various Java frameworks like Hibernate & Spring.

Got a question for us? Please mention it in the comments section of this “HashSet in Java” article and we will get back to you as soon as possible.

Upcoming Batches For Java Course Online
Course NameDateDetails
Java Course Online

Class Starts on 7th December,2024

7th December

SAT&SUN (Weekend Batch)
View Details
Comments
0 Comments

Join the discussion

Browse Categories

webinar REGISTER FOR FREE WEBINAR
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP

Subscribe to our Newsletter, and get personalized recommendations.

image not found!
image not found!

Learn what is HashSet in Java and how to get started with it!

edureka.co