Skip to main content

HashSet in Java

HashSet in Java

In this article, we are going to learn about what is HashSet in Java. We also look at the methods provided by the HashSet in Java, how HashSet internally managed by Java and all.


What is HashSet in Java?

HashSet in java, is an implementation of Set interface of Java i.e., duplicate elements are not allowed. A Set is similar to a List but duplicate elements are allowed in a List.
HashSet is the part of Java Collection Framework. It is defined in java.util package and implements Set interface which provides standard method declaration to perform basic operation like store, retrieve data from the HashSet and etc.
HashSet internally maintains a HashMap as its internal data structure, so that all the operation made on the HashSet transparently done on the HashMap.
Declaration of HashMap within the HashSet in Java
public class HashSet<E>{
        private transient HashMap<E,Object> map; 
        private static final Object PRESENT = new Object();
}
As we can see, the type of HashSet is same as the key type of HashMap i.e., all the elements added to the HashSet will become the Keys of HashMap and a constant value of Object type is associated with the each key of the HashMap (i.e., elements of the HashSet) named as PRESENT.

Note : To understand HashSet in java properly, first we should understand what is HashMap in java and how HashMap works internally in java.

Important point to remember about the HashSet in Java

  • HashSet in java is an implementation of Set Interface i.e., duplicate elements are not allowed.
  • HashSet works on the Principle of Hashing.
  • HashSet in Java internally maintains a HashMap data structure. All the methods provided by the HashSet internally works upon the HashMap.
  • HashSet in a generic class i.e., It can store any type of elements.
  • HashSet cannot store any primitive type elements, for that we can use wrapper classes as the type of HashSet. For example Integer class instead of int primitive.
  • The insertion order is not maintained by the HashSet in java as it maintains a HashMap type data structure.
  • Only one null value can be stored in the HashSet as duplicates are not Allowed
  • HashSet in java, is not synchronized among the threads, we have to make it synchronized by our-self.

Time complexity of HashSet in Java?

Time complexity to store and retrieve data from the HashSet in Java is same as of the HashMap. O(1) in the Best Case, but it can be O(n) in the worst case and after the changes made in Java 8 the worst case time complexity can be O(log n) atmost.

Hierarchy of the HashSet in java?

Declaration of HashSet
public class HashSet<E>
    extends AbstractSet<E>
    implements Set<E>, Cloneable, java.io.Serializable {
     ----------------
}

AbstractSet<E>

The AbstractSet<E> provides a basic and abstract implementation of the Set Interface to the HashSet. Also, AbstractSet<E> extends the AbstractCollection<E> which provides the abstract implementation of the Collection Interface.

Why Cloneable?

Cloneable is a marker interface and it is a part of java.lang package. A class implements this interface if it wants to call the clone() method of Object class using super keyword i.e., super.clone(); through any method or any constructor. If that class does not implement this marker interface and invoke the i.e., super.clone(); then java.lang.CloneNotSupportedException will be raised.
HashSet in Java, provides overrode clone() method that internally calls the actual clone() method of Object class. So, HashSet needs to implement this marker interface.
Note : The clone() method of Object class is used to create a cloned object.

Why Serializable?

Serializable is a marker interface and it is a part of java.io package. If Any class implements this interface then the class can be serialized or deserialized. Serialization is a process in which an object is converted into the byte stream and Deserialization is the reverse of serialization i.e., byte stream to java object. Serialization helps us to store and retrieve objects from and to files, databases, networks, etc. The only class marked with the Serializable interface can be serialized or deserialized.
HashSet in Java often needs to store and retrieve the object from the files, databases, etc. That's why HashSet is implemented as Serializable.

How to create object of HashSet in java?

Using Default Constructor

HashSet<String> hashSet = new HashSet<>();
The HashSet is instantiated using the default constructor and the type of HashSet is declared as the "String".

Using Constructor which require another Collection

A HashSet in Java can be created from another Collection and Collection can be a List,Set etc.
ArrayList<String> books = new ArrayList<>();
books.add("Programming In Java");
books.add("Computer Networks");
books.add("Introduction to Algorithms");
books.add("Data Structures");
HashSet<String> copyBookSet = new HashSet<>(books);
System.out.println(copyBookSet);
Output
[Computer Networks, Programming In Java, Introduction to Algorithms, Data Structures]

How to add elements to the HashSet in java?

The add() method is used to add elements into the HashSet one at a time. This method takes one argument and store into the HashSet in java.
Syntax of add() method
boolean result = hashSet.add(element);
This method returns true if a new element is added to the HashSet, Otherwise false which states HashSet has not modified. In most of the case, we don't use the boolean value returned by the add() as it only signifies that the element is new or not.
Internal Definition of add() method
public boolean add(E e) {
        return map.put(e, PRESENT)==null;
}
The above expression map.put(e, PRESENT)==null; returns true if a new is added to the map as the put() method returned null if a new key is added to the HashMap otherwise previous value associated with that key.

Java HashSet Example 1 : Create a set of books and few books into them

HashSet<String> bookSet = new HashSet<>();
bookSet.add("Programming In Java");
bookSet.add("Computer Networks");
bookSet.add("Introduction to Algorithms");
bookSet.add("Data Structures");
System.out.println(bookSet);
Output
[Computer Networks, Programming In Java, Introduction to Algorithms, Data Structures]

How to iterate HashSet in java?

In java, there exist the number of approaches to iterate HashSet in Java. Let's look at a few of them which come in day-to-day programming practices.

Using for-each loop

Java HashSet Example 2 : Iterate the HashSet in Java using for each loop and print all the books

for(String book : bookSet) {
      System.out.println(book);
}
Output
Computer Networks
Programming In Java
Introduction to Algorithms
Data Structures

Using Iterators

Java HashSet Example 3 : Iterate the HashSet in Java using iterators and print all the books

Iterator<String> iterator = bookSet.iterator();
while(iterator.hasNext()){
      String book = iterator.next();
      System.out.println(book);
}
Output
Computer Networks
Programming In Java
Introduction to Algorithms
Data Structures

Using forEach() method

Java HashSet Example 4 : Iterate the HashSet in Java using forEach() method and print all the books

bookSet.forEach(book -> System.out.println(book));
Output
Computer Networks
Programming In Java
Introduction to Algorithms
Data Structures

How to check whether an elements is stored in the HashSet in Java?

To check whether an element is present into the HashSet or not, HashSet in Java provides a method called contains() method. This method takes an argument and returns true if the HashSet contains the specified element.
Syntax of contains() method
boolean result = hashSet.contains(element);
Internal Definition of contains() method
public boolean contains(Object o) {
        return map.containsKey(o);
}
Internally containsKey() method of the HashMap is invoked and return true if the HashMap contains that element as the Key.

Java HashSet Example 5 : Check whether "Computer Networks" is contained within the HashSet or not

HashSet<String> bookSet = new HashSet<>();
bookSet.add("Programming In Java");
bookSet.add("Computer Networks");
bookSet.add("Introduction to Algorithms");
bookSet.add("Data Structures");
if(bookSet.contains("Computer Networks")) {
        System.out.println("HashSet contains Computer Networks");
}
Output
HashSet contains Computer Networks

How to remove elements from the HashSet in java?

Using remove(object) method

The remove(object) method is used to remove the specified element from the HashSet in Java. This method return true if the element is present and successfully removed.
Syntax of remove() method
boolean result = hashSet.remove(element);
Internal Definition of remove() method
public boolean remove(Object o) {
        return map.remove(o)==PRESENT;
}
Internally remove() method of the HashMap is invoked. In-actual, the mapping is removed from the HashMap and returns the value associated with the key, which will always be PRESENT if the key is found in the HashMap otherwise null is returned.

Java HashSet Example 6 : Remove "Computer Networks" named book from the HashSet in Java

HashSet<String> bookSet = new HashSet<>();
bookSet.add("Programming In Java");
bookSet.add("Computer Networks");
bookSet.add("Introduction to Algorithms");
bookSet.add("Data Structures");
System.out.println("HashSet values : " + bookSet);
if(bookSet.remove("Computer Networks")) {
        System.out.println("Computer Networks is successfully removed");
}
System.out.println("HashSet values : " + bookSet);
Output
HashSet values : [Computer Networks, Programming In Java, Introduction to Algorithms, Data Structures]
Computer Networks is successfully removed
HashSet values : [Programming In Java, Introduction to Algorithms, Data Structures]

Using removeIf() method

To remove object on the basis of some conditions we can use removeIf() method. The removeIf() method takes an argument of java.util.Predicate type, apply that predicate to each element of HashSet in Java and remove all those element which satisfies the given predicate.

Java HashSet Example 7 : Create a new HashSet of cities and remove all the cities that is not from India

HashSet<String> cities = new HashSet<>();
cities.add("Delhi-India");
cities.add("New York-USA");
cities.add("Mumbai-India");
cities.add("Kolkata-India");
cities.add("London-England");
System.out.println("-------------Cities : Before removing---------------");
System.out.println(cities);
cities.removeIf(city -> !city.contains("India"));
System.out.println("-------------Cities : After removing----------------");
System.out.println(cities);
Output
-------------Cities : Before removing---------------
[Delhi-India, New York-USA, Kolkata-India, Mumbai-India, London-England]
-------------Cities : After removing----------------
[Delhi-India, Kolkata-India, Mumbai-India]
Note : The city -> !city.contains("India") is the lambda representation of the Predicate class. Predicate is a Functional Interface which in introduced in Java 8. To know more about the Function interface and Lambda Expression read these article : Functional Interface in Java and Lambda Expression in Java.

Few more methods of HashSet in java

size() : This method returns the size of HashSet in Java i.e., how many elements are stored in the HashSet.
clear() : This method removes all elements from the HashSet and make it empty.
isEmpty() : This method returns true if the HashSet is not containing any elements in it otherwise false.

Java HashSet Example 8 : Different States of HashSet in Java

HashSet<String> cities = new HashSet<>();
cities.add("Delhi-India");
cities.add("New York-USA");
cities.add("Mumbai-India");
cities.add("Kolkata-India");
cities.add("London-England");
System.out.println("How many cities are there in the HashSet? : " + cities.size());

System.out.println("Removing all elements from the HashSet.....");
cities.clear();

if(cities.isEmpty()) {
       System.out.println("HashSet is Empty Now");
}
Output
How many cities are there in the HashSet? : 5
Removing all elements from the HashSet.....
HashSet is Empty Now

How to create Array from HashSet in Java?

To create array from the HashSet in java, here is a method of HashSet which is toArray(T[] a) method. This method copy all the elements of the HashSet into the provided array (as the argument), if the size of the array is greater than or equal to the number of elements present in the HashSet otherwise a new array created and returned by this method.
Syntax of toArray()
T[] toArray(T[] a)

Java HashSet Example 9 : Create an array of cities from the HashSet in Java

HashSet<String> cities = new HashSet<>();
cities.add("Delhi-India");
cities.add("New York-USA");
cities.add("Mumbai-India");
cities.add("Kolkata-India");
cities.add("London-England");
String[] cityArray = new String[cities.size()];
cities.toArray(cityArray);
System.out.println("Array of City : ");
for(String city : cityArray) {
      System.out.println(city);
}
Output
Array of City : 
Delhi-India
New York-USA
Mumbai-India
Kolkata-India
London-England

How to sort HashSet in Java?

To sort a HashSet in java, we need to create a ArrayList from the HashSet and then we can sort Arraylist in java. For example :

Java HashSet Example 10 : Create an ArrayList from HashSet and sort the ArrayList

HashSet<String> cities = new HashSet<>();
cities.add("Delhi-India");
cities.add("New York-USA");
cities.add("Mumbai-India");
cities.add("Kolkata-India");
cities.add("London-England");
System.out.println("Unsorted cities : " + cities);

ArrayList<String> cityList = new ArrayList<>(cities);
Collections.sort(cityList);
System.out.println("Sorted cities : " + cityList);
Output
Unsorted cities : [Mumbai-India, Delhi-India, Kolkata-India, London-England, New York-USA]
Sorted cities : [Delhi-India, Kolkata-India, London-England, Mumbai-India, New York-USA]
To know more about how to sort ArrayList in java, read this article : How to sort Arraylist in java

Related Article


Conclusion

In this article, we have learned about the HashSet in java, what it is and methods of HashSet In java. We have also learned how to create an array from HashSet and how to sort a HashSet in Java.

Comments

Popular posts from this blog

How HashMap works internally in java

How Hashmap works Internally in Java In this article, we are going to see how HashMap internally works in java. Also, we will have a look at what Java 8 made changes on the internal working of Hashmap to make it faster. What is Hashmap and Hashing in java? How Hashmap works Internally in Java is majorly dependent upon the Hashing Principle. So, Before going to learn how HashMap works internally in java, lets first understand what is HashMap and hashing. HashMap : A HashMap is a map used to store mappings of key-value pairs. Also, it works on the Principle of Hashing. To know more about the HashMap, visit this article: HashMap in Java Hashing Principle : Simply, Hashing is a method used to produce an integer value from an object and this integer value known as the hash value. In HashMap, the key object is used for Hashing.
Internal Struture of the HashMap in java For internal working of HashMap, HashMap maintains an array of bucket, each bucket is a linked-list and linked list is a li…

HashMap in Java

HashMap in Java In this article, we are going to learn about the most important class of Java known as HashMap. HashMap in java is the most used map interface and it is used in our regular or day-to-day programming practices.
What is HashMap in java? Lets first start with basic definition of HashMap,
HashMap is a map which store key-value pair, where each key is mapped with a value.
HashMap defined in java.util package and implements map interface which provides functionalities to perform basic operation like store, retrieve, size of the map etc. It is a part of Java Collection Framework. Time complexity of HashMap in Java? : Time complexity to store and retrieve data from the HashMap is O(1) in the Best Case. But it can be O(n) in the worst case and after the changes made in Java 8 the worst case time complexity can be O(log n) atmost. Internal working of HashMap in java HashMap maintains an array of the buckets, where each bucket is a linked-list and the linked list is a list of…

ArrayList in Java

ArrayList in Java In this article, we are going to discuss ArrayList in Java. ArrayList is a class from the Java Collection Framework and widely in our programs. We use ArrayList as a substitute for the array. So, it is important to know ArrayList in detail. We are going to see what is ArrayList in Java, how we can create the instance of ArrayList and the methods provided by the ArrayList in Java.

If you already familiar to ArrayList, you may learn common programs related to ArrayList.
Table of ContentsWhat is ArrayList in Java?Hierarchy of the ArrayList in java?How to create objects of ArrayList in Java?How to create an ArrayList of Custom Objects?How to iterate ArrayList in Java?How to get the elements by index from ArrayList in Java?How to check whether an elements is stored in the ArrayList in Java?How to remove elements from the ArrayList in Java?Few more methods of ArrayList in Java?
What is ArrayList in Java? ArrayList in Java is a List in which we can store and retrieve elemen…