Monday, November 1, 2021

How to use HashSet in Java? Set Example Tutorial

Hello friends, we meet again for our journey of learning Java. Today, we are gonna learn something very fruitful and easy. Hope you all are excited and ready. I would recommend you guys to go through the HashMap or TreeMap article which goes over hashing as this topic has some of its features. So, What's the wait? Let's start! Suppose you guys are given the task of storing car names (yes, I love cars :p). Now, how would you store it? If you guys have some questions, here are the requirements. The car names may increase over time. So, logically, an array is not what we are looking for. 

So, you guys must be thinking that we can store them in an ArrayList. yes, that's true. But, as we know there can only be 1 car name associated with 1 car, we know that all names are gonna be unique. Can we use this information to decrease the time complexity of searching an ArrayList

Think for a few minutes and keep in mind something about hashing :p

I know you guys are now thinking that we can use a HashMap here. As the names are unique, we can store the names as keys in the hashmap. 

But, what about the values? Let it be empty? or should we keep the same car names as a value too? Do you think it is justifiable to keep the redundant data? Of course no. so, let's see what today's topic has us to offer and observe what we can do with it.






HashSet in Java:

The HashSet class in Java is used to construct a collection that stores data in a hash table. It derives from AbstractSet and implements the Set interface. The iteration order of the set is not guaranteed, which implies that the class does not ensure that the order of the items will remain consistent throughout time. The null element is allowed in this class. 

The class also provides constant-time performance for fundamental operations like as add, remove, contains, and size, providing that the hash function appropriately distributes the elements across the buckets, as we'll see later in the article.

HashSet extends Abstract SetE> and implements the SetE>, Cloneable, and Serializable interfaces, where E denotes the type of items this set keeps track of. LinkedHashSet is the only directly known HashSet subtype.

How to use HashSet in Java? Set Example Tutorial


Iterating through HashSet takes time proportional to the sum of the HashSet instance's size (the number of items) plus the underlying HashMap instance's "capacity" to maintain constant time performance (the number of buckets). If iteration performance is essential, it's crucial not to set the starting capacity too high (or the load factor too low).

In the sense that if several threads access a hash set concurrently and at least one of the threads alters the set, it must be synchronized externally, the implementation in a HashSet is not synchronized. 

This is usually achieved by synchronizing on a natural encapsulation object for the set. If no such object exists, use the Collections.synchronizedSet method to "wrap" the set.

Let's see how it is used as implementation is concerned.



Code:

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

public class MyHashSet {
public static void main(String[] args) {
Set<String> myCarSet = new HashSet<>();

myCarSet.add("BMW M3");
myCarSet.add("Audi A8");
myCarSet.add("Mercedes Q3");
myCarSet.add("Bugatti veyron");
myCarSet.add("Ferrari spider");

myCarSet.forEach(a -> System.out.print(a+" "));

System.out.println("Traversal completed!");

if(myCarSet.contains("BMW M3")) System.out.println("Yes! BMW hai");

myCarSet.remove("BMW M3");

System.out.println("Traversal started!");

myCarSet.forEach(a -> System.out.print(a + " "));

System.out.println("Traversal completed!");
}
}



Output:



Now, that you guys have seen the implementation, you can see yourself as how much fast, efficient and easy it is to use HashSet.  Let's see some of the important points of Hashset.

Internal workings of a HashSet: 

Map backs up all Set interface classes internally. Internally, HashSet stores its object using HashMap. You might be asking why, in HashMap, we require a key-value pair to input a value, while in HashSet, we just pass one value.

In a HashMap, the value we put in the HashSet works as a key to the map Object, and java utilises a constant variable to store the value. As a result, all of the values in a key-value pair will be the same.

HashSet uses the hashCode() and equals() methods to verify if there is an existing entry before saving an Object. Two lists are deemed equal in the preceding example if they have the same entries in the same order. Because the two lists are equal, they will both return the same hash when you use the hashCode() function on them. 

HashSet does not keep duplicate items; if you give it two identical objects, it will only store the first one. HashSet operations are time-consuming because the underlying data structure is a hashtable. As a result, amortise (average or common case) time complexity for HashSet operations like add, remove, and look-up (contains method) is O(1).


That's all about how to use HashSt in Java. Hashset is an important class of Java Collection framework and very useful if you want to store unique elements or want to avoid duplicates. As I have explained, HashSet is backed by HashMap which is an hash table, hence it provides O(1) performance for adding and retriving objects. 


Thanks for reading this article if you find these Java HahsSet examples useful then please share them with your friends and colleagues. If you have any questions or feedback then please drop me a note. 

P. S. - If you are new to Java and looking for a free course to learn Java in a structured way then you can also check this Java Tutorial for Complete Beginners(FREE) course on Udemy. It's completely free and more than 1.4 million developers have joined this course. You just need a free Udemy account to join the course. 

No comments:

Post a Comment

Feel free to comment, ask questions if you have any doubt.