How to Implement a Bidirectional Map Using Two HashSets in Java? Last Updated : 07 Feb, 2024 Comments Improve Suggest changes Like Article Like Report 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 JavaBelow is the code implementation to implement a bidirectional map using two HashSets. Java // Java Program to implement a bidirectional map using two HashSets import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; public class BidirectionalMap<K, V> { private final Map<K, V> keyToValueMap = new HashMap<>(); private final Map<V, K> valueToKeyMap = new HashMap<>(); // method to put a key-value pair into the bidirectional map public void put(K key, V value) { keyToValueMap.put(key, value); valueToKeyMap.put(value, key); } // method to get a value based on the key public V getValueByKey(K key) { return keyToValueMap.get(key); } // method to get a key based on the value public K getKeyByValue(V value) { return valueToKeyMap.get(value); } // method to check if a key exists in the map public boolean containsKey(K key) { return keyToValueMap.containsKey(key); } // method to check if a value exists in the map public boolean containsValue(V value) { return valueToKeyMap.containsKey(value); } // method to remove a key-value pair based on the key public void removeByKey(K key) { V value = keyToValueMap.remove(key); valueToKeyMap.remove(value); } // method to remove all key-value pairs from the bidirectional map public void removeAll() { keyToValueMap.clear(); valueToKeyMap.clear(); } // method to get a set of all keys in the bidirectional map public Set<K> getAllKeys() { return keyToValueMap.keySet(); } // method to get a set of all values in the bidirectional map public Set<V> getAllValues() { return valueToKeyMap.keySet(); } // Main method to demonstrate the usage of the BidirectionalMap class public static void main(String[] args) { // Create a BidirectionalMap with Integer keys and String values BidirectionalMap<Integer, String> biMap = new BidirectionalMap<>(); // Add key-value pairs biMap.put(1, "One"); biMap.put(2, "Two"); biMap.put(3, "Three"); // Retrieve values by key System.out.println("Value for key 2: " + biMap.getValueByKey(2)); // Retrieve keys by value System.out.println("Key for value 'Three': " + biMap.getKeyByValue("Three")); // checks if a key or value exists System.out.println("Contains key 4: " + biMap.containsKey(4)); System.out.println("Contains value 'One': " + biMap.containsValue("One")); // Remove a key-value pair biMap.removeByKey(1); // Display all keys and values System.out.println("All keys: " + biMap.getAllKeys()); System.out.println("All values: " + biMap.getAllValues()); // Clear the map biMap.removeAll(); // checks if the map is empty after clearing System.out.println("Is the map empty? " + (biMap.getAllKeys().isEmpty() && biMap.getAllValues().isEmpty())); } } OutputValue 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 More infoAdvertise with us Next Article How to Implement a Bidirectional Map Using Two HashSets in Java? S shivanshmahajan876 Follow Improve Article Tags : Java Java Programs HashSet java-hashset Java Examples +1 More Practice Tags : Java Similar Reads How to Convert a HashSet to JSON in Java? In Java, a HashSet is an implementation of the Set interface that uses a hash table to store elements. It allows fast lookups and does not allow duplicate elements. Elements in a HashSet are unordered and can be of any object type. In this article, we will see how to convert a HashSet to JSON in Jav 2 min read How to Implement a Custom Hash function for Keys in a HashMap in Java? In Java, HashMap is the data structure that implements the Map interface. This is used to save the data in the form of key-value pairs. In this article, we will learn how to implement a Custom Hash function for keys in a HashMap in Java. In Java, implementing the custom hash function for keys in a H 2 min read Java Program to Implement Hash Tables with Double Hashing Double hashing is a technique in an open addressing scheme. and there is the ordinary hash function. In an open addressing scheme, the actual hash function is taking the ordinary hash function when its space is not empty then it will perform another hash function to get some space to insert. Double 10 min read Java Program to Implement HashTable API The Hashtable class implements a hash table, which maps keys to values. Any non-null object can be used as a key or as a value. To successfully store and retrieve objects from a hashtable, the objects used as keys must implement the hashCode method and the equals method. To implement Hashtable API f 4 min read How to Merge Two HashMaps in Java while Handling Conflicts? HashMap is a part of the collection framework found in Java. It is found in the java.util package and provides the basic implementation of the Map interface of Java. Conflict handling is very important in HashMap as if they are ignored the code will not work properly. In this article, we will learn 3 min read How to Convert a HashTable to Other Collections Types in Java? In Java, a Hashtable is a data structure that stores the data in the form of key and value pairs. And each key is mapped to a specific value. It implements the Map interface. HashTable provides a simple way to access the data using the unique keys. In this article, we will learn how to convert a Has 3 min read Java Program to Implement Hash Table Chaining with List Heads A hash table is a data structure that executes a connected array, it is a structure that maps keys to its values. It uses a hash function to calculate an index position for the keys, also called hash code. It will store key and value pair in an array of buckets, and from that bucket, the values can 4 min read How to Convert List of Lists to HashSet in Java? In Java, Collections like lists, and sets play a crucial role in converting and manipulating the data efficiently. The Conversion of a List of Lists into a HashSet is mainly used to Remove Duplicates and ensures the programmer maintains the unique data of elements. Example to Convert List of Lists t 2 min read Java Program to Implement ConcurrentHashMap API ConcurrentHashMap class obeys the same functional specification as HashTable and includes all the versions of methods corresponding to each method of a HashTable. A HashTable supports the full concurrency of retrievals and adjustable concurrency for updates. All the operations of ConcurrentHashMap a 6 min read How to Get a Value From LinkedHashMap by Index in Java? LinkedHashMap is a predefined class in Java which is similar to HashMap, contain key and its respective value unlike HashMap, In LinkedHashMap insertion order is preserved. The task is to get value from LinkedHashMap by their Index in other words, an order of their insertion. As an advantage of Link 4 min read Like