VOOZH about

URL: https://www.geeksforgeeks.org/java/how-to-implement-a-bidirectional-map-using-two-hashsets-in-java/

⇱ How to Implement a Bidirectional Map Using Two HashSets in Java? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to Implement a Bidirectional Map Using Two HashSets in Java?

Last Updated : 23 Jul, 2025

Bidirectional maps are also known as two-way maps or dual maps. These provide a convenient way to establish a relationship between keys and values in both directions. In Java, we can implement these using HashSet.

So, in this article, we will see how to implement bidirectional maps in Java using two Hash Sets.

Bidirectional Map Implementation:

A bidirectional map created a relation where each element in one set corresponds to a unique element in another set. This article explores the implementation of bidirectional maps in Java using HashSet collections of Java. The main idea is to maintain two Maps. First for the forward direction and second for the reverse direction.

Program to Implement a Bidirectional Map Using Two HashSets in Java

Below is the code implementation to implement a bidirectional map using two HashSets.


Output
Value for key 2: Two
Key for value 'Three': 3
Contains key 4: false
Contains value 'One': true
All keys: [2, 3]
All values: [Two, Three]
Is the map empty? true

Explanation of the Program:

  • The above Java program implements a Bidirectional Map. It allows mapping between keys and values in both directions.
  • It uses two separate HashMaps for efficient bidirectional lookups.
  • The BidirectionalMap class provides methods for putting key-value pairs, retrieving values by key, retrieving keys by value, checking if a key or value exists, removing key-value pairs, and accessing all keys and values.
  • The main method demonstrates the usage of this BidirectionalMap with Integer keys and String values.
  • It shows various operations such as adding pairs, retrieving values and keys, checking existence, removing pairs, displaying all keys and values, and clearing the map.
Comment