Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What is HashMap?
2.1.
Features of HashMap
2.2.
Implementation of a HashMap
2.2.1.
Code
2.3.
java
3.
What is HashSet?
3.1.
Features of HashSet
3.2.
Implementation of HashSet
3.2.1.
In Java, HashSet is the other data structure. It is implemented by using a hash table. It is used to store unique elements. HashMap is used in HashSet to store its elements internally. By using the add() method, elements are added to HashSet. It takes an element as a parameter. Then the element is hashed and stored in HashMap as a key with some value. Let’s have a look at Implementation of HashSet code:Code
3.3.
java
4.
Difference between HashMap and HashSet
5.
Frequently Asked Questions
5.1.
What is the main difference between HashMap and HashSet?
5.2.
How can we add elements to HashMap and HashSet?
5.3.
How many null keys are allowed in HashMap?
5.4.
Can HashMap and HashSet be used interchangeably?
6.
Conclusion
6.1.
Recommended Reading: 
Last Updated: Mar 27, 2024
Medium

Difference between HashMap and HashSet

Author Monika Yadav
1 upvote

Introduction

Java HashMap is a Map that uses a hash table for storage, while HashSet is a Set that also employs a hash table for storage.

Difference between HashMap and HashSet

In this blog, we will learn about HashMap and HashSet Features, Implementation, and their differences. Now let’s go ahead in the blog and learn more interesting differences between HashMap and HashSet.

Also see,  Swap Function in Java

What is HashMap?

In Java, HashMap is commonly used. It is useful in a wide range of applications, such as caching systems, database operations, and more. HashMap is a class. It is used to store and retrieve key-value pairs. It is a part of the Java Collections Framework. It also provides a flexible and efficient way to map keys to their corresponding values. In a HashMap, keys are unique and are used to retrieve their associated values. The values can be of any data type, such as strings, integers, or custom objects. HashMap uses a hash function to map keys to their corresponding values, allowing fast retrieval times.

Features of HashMap

Some of the features of HashMap in Java are given below:

  1. Iterability: HashMap can be iterated over using iterators, which allow for easy traversal of the key-value pairs stored in the HashMap.
     
  2. Null Values: HashMap allows null values to be stored as keys or values.
     
  3. Fast Lookup: HashMap uses a hash function to map keys to their corresponding values, which allows for fast lookup times. The time complexity on average for operations like put(), get(), and remove() is O(1).
     
  4. Resizable: HashMap can resize dynamically based on the number of elements it contains.
     
  5. Not Thread-safe: HashMap is not thread-safe. It also requires synchronization if used in a multi-threaded environment. In such cases, ConcurrentHashMap can be used instead.

Implementation of a HashMap

In Java, HashMap is a data structure. It allows us to store and retrieve key-values. It is an array of  buckets for implementation. Here each bucket is a linked list of entries. Each entry in the linked list stores a key-value pair and a next entry in the list. The key is first hashed to generate an index in the bucket array then stored in HashMap. Then the key value pair is added to the linked list. To retrieve a value, the linked list is searched for an entry with the same key. Let’s have a look at Implementation of HashMap code:

Code

  • java

java

import java.util.*;

public class HashMapCode {
static class HashMap<K,V> {
private class Node {
K key;
V value;
public Node(K key, V value) {
this.key = key;
this.value = value;
}
}
private int n;
private int N;
private LinkedList<Node> buckets[];
public HashMap() {
this.N = 4;
this.buckets = new LinkedList[4];
for(int i=0; i<4; i++) {
this.buckets[i] = new LinkedList<>();
}
}
private int hashFunction(K key) {
int bi = key.hashCode();
return Math.abs(bi) % N;
}
private int searchInLL(K key, int bi) {
LinkedList<Node> ll = buckets[bi];
for(int i=0; i<ll.size(); i++) {
if(ll.get(i).key == key) {
return i;
}
}
return -1;
}
private void rehash() {
LinkedList<Node> oldBucket[] = buckets;
buckets = new LinkedList[N*2];
for(int i=0; i<N*2; i++) {
buckets[i] = new LinkedList<>();
}
for(int i=0; i<oldBucket.length; i++) {
LinkedList<Node> ll = oldBucket[i];
for(int j=0; j<ll.size(); j++) {
Node node = ll.get(j);
put(node.key, node.value);
}
}
}
public void put(K key, V value) {
int bi = hashFunction(key);
int di = searchInLL(key, bi);
if(di == -1) {
buckets[bi].add(new Node(key, value));
n++;
} else {
Node node = buckets[bi].get(di);
node.value = value;
}
double lambda = (double)n/N;
if(lambda > 2.0) {
rehash();
}
}
public boolean containsKey(K key) {
int bi = hashFunction(key);
int di = searchInLL(key, bi);
if(di == -1) {
return false;
} else {
return true;
}
}
public V remove(K key) {
int bi = hashFunction(key);
int di = searchInLL(key, bi);
if(di == -1) {
return null;
} else {
Node node = buckets[bi].remove(di);
n--;
return node.value;
}
}
public V get(K key) {
int bi = hashFunction(key);
int di = searchInLL(key, bi);
if(di == -1) {
return null;
} else {
Node node = buckets[bi].get(di);
return node.value;
}
}
public ArrayList<K> keySet() {
ArrayList<K> keys = new ArrayList<>();
for(int i=0; i<buckets.length; i++) {
LinkedList<Node> ll = buckets[i];
for(int j=0; j<ll.size(); j++) {
Node node = ll.get(j);
keys.add(node.key);
}
}
return keys;
}
public boolean isEmpty() {
return n == 0;
}
}

public static void main(String args[]) {
HashMap<String, Integer> map = new HashMap<>();
map.put("Ninja1", 70);
map.put("Ninja2", 80);
map.put("Ninja3", 90);
ArrayList<String> keys = map.keySet();
for(int i=0; i<keys.size(); i++) {
System.out.println(keys.get(i)+" "+map.get(keys.get(i)));
}
map.remove("Ninja1");
System.out.println(map.get("Ninja1"));
}
}

Output

Output
Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

What is HashSet?

In Java, HashSet is a commonly used data structure. It is useful in a wide range of applications, such as checking for duplicates, filtering data, and more. HashSet is a class. It is used to store a collection of unique elements. It is a part of the Java Collections Framework and provides an efficient way to store and manipulate a group of elements without duplicates. In a HashSet, elements are unique and unordered, and the order in which they are stored may vary. The elements can be of any data type, such as strings, integers, or custom objects. HashSet uses a hash function to map elements to their corresponding buckets, which allows for fast lookup times.

Features of HashSet

Some of the key features of HashSet in Java:

  1. Stores Unique Elements: HashSet is used to store a collection of unique elements. 
     
  2. Iterability: HashSet can be iterated over using iterators. 
     
  3. Allows Null Values: HashSet allows null values to be stored as elements.
     
  4. Not Thread-safe: HashSet is not thread-safe and requires synchronization if used in a multi-threaded environment. In such cases, Concurrent HashSet can be used instead.
     
  5. Fast Lookup: HashSet uses a hash function to map elements to their corresponding buckets, which allows for fast lookup times. On average, the time complexity for operations like add(), contains(), and remove() is O(1).
     
  6. Resizable: HashSet can resize dynamically based on the number of elements it contains, which allows for efficient use of memory.
     
  7. Ordering: HashSet does not maintain any order of the elements stored in it. However, LinkedHashSet can be used instead if order needs to be maintained.

Implementation of HashSet

In Java, HashSet is the other data structure. It is implemented by using a hash table. It is used to store unique elements. HashMap is used in HashSet to store its elements internally. By using the add() method, elements are added to HashSet. It takes an element as a parameter. Then the element is hashed and stored in HashMap as a key with some value. Let’s have a look at Implementation of HashSet code:

Code

  • java

java

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

public class Hashing {
  public static void main(String args[]) {
      HashSet<Integer> set = new HashSet<>();
      set.add(1);
      set.add(2);
      set.add(3);
      set.add(4);
      System.out.println("size of set is : " + set.size());
      if(set.contains(2)) {
          System.out.println("2 is present ");
      }
      if(!set.contains(7)) {
          System.out.println("7 is not present");
      }
      set.remove(1);
      if(!set.contains(1)) {
          System.out.println("1 is not present");
      }
      System.out.println(set);
      set.add(0);
      Iterator it = set.iterator();
       while (it.hasNext()) {
          System.out.print(it.next() + ", ");
      }
      System.out.println();
      if(!set.isEmpty()) {
          System.out.println("set is not empty");
      }
  }
}


Output

Output

Difference between HashMap and HashSet

Here is a comparison between HashMap and HashSet:

Feature

HashMap

HashSet

Storage

Stores key-value pairs

Stores unique elements

Duplicate

Can have duplicate values but not duplicate keys

Cannot have duplicate elements

Retrieval

Uses key to retrieve value

Uses element to check if it exists

Time complexity (average case)

O(1) for get(), put(), and remove() operations O(1) for add(), contains(), and remove() operations

Ordering

No specific order maintained

No specific order maintained

Thread-Safety

Not thread-safe

Not thread-safe

Internal implementation

Uses a hash table to store key-value pairs

Uses a hash table to store unique elements

Also read, What is the Difference Between HashSet and TreeSet?

Frequently Asked Questions

What is the main difference between HashMap and HashSet?

The main difference is that HashMap stores key-value pairs whereas HashSet stores unique elements without any associated values.

How can we add elements to HashMap and HashSet?

In the case of HashMap, put(key, value) method is used to add a key-value pair. In HashSet, you use the add(element) method to add an element.

How many null keys are allowed in HashMap?

Only one null key is allowed. This is because HashMap uses the key's hash code to determine its storage location, and multiple null keys would all have the same hash code, leading to conflicts.

Can HashMap and HashSet be used interchangeably?

No, HashMap and HashSet cannot be used interchangeably. As they serve different purposes. If users need to associate values with keys, users should use HashMap. If users need to store a collection of unique elements, use HashSet.

Conclusion

We hope this article helped you understand the difference between HashMap and HashSet. We have also discussed the Introduction, features and implementation of HashMap and HashSet. Do read below articles to enhance your knowledge. 

Recommended Reading:
 

Check out some of the amazing Guided Paths on topics such as Data Structure and AlgorithmsCompetitive ProgrammingBasics of C, Basics of JavaOperating SystemsComputer Networks, etc., along with some Contests and Test Series only on Coding Ninjas StudioEnrol in our courses and refer to the mock test and problems available. Take a look at the interview experiences and interview bundle for placement preparations. 

Happy Coding!

Previous article
Introduction to Hash Map
Next article
HashMap entrySet() Method in Java
Live masterclass