Wednesday 22 May 2019

Java: Implement Bidirectional Map


Bidirectional map preserves the uniqueness of its values as well as that of its keys. You can get the value from key, and key from value.

By extending any of the existing maps implementations, you can create a bidirectional map.

BiMap.java
package com.sample.app;

import java.util.HashMap;
import java.util.Map;

public class BiMap<K, V> extends HashMap<K, V> {
 private static final long serialVersionUID = 1L;
 public Map<V, K> inversedMap = new HashMap<V, K>();

 public K getKey(V value) {
  return inversedMap.get(value);
 }

 @Override
 public int size() {
  return this.size();
 }

 @Override
 public boolean isEmpty() {
  return this.size() > 0;
 }

 @Override
 public V remove(Object key) {
  V val = super.remove(key);
  inversedMap.remove(val);
  return val;
 }

 @Override
 public V get(Object key) {
  return super.get(key);
 }

 @Override
 public V put(K key, V value) {
  inversedMap.put(value, key);
  return super.put(key, value);
 }

}


App.java
package com.sample.app;

public class App {

 public static void main(String args[]) {
  BiMap<Integer, Integer> map = new BiMap<>();

  map.put(10, 20);
  map.put(11, 21);

  System.out.println("10 -> " + map.get(10));
  System.out.println(map.getKey(21) + " -> 21");
 }
}

Output
10 -> 20
11 -> 21


You may like


No comments:

Post a Comment