One interesting way to implement this is with a view approach that allows you to link Dictionary and Map together and are fully functional. As shown in the following code example:
Dictionary<String, String> dict = new Hashtable<>(); dict.put("PT", "Portugal"); dict.put("CH", "Switzerland"); System.out.println(dict); Map<String, String> map = MapUtils.asMap(dict); System.out.println(map); map.remove("CH"); dict.put("UK", "United Kingdom"); System.out.println(dict); System.out.println(map); map.clear(); System.out.println(dict); System.out.println(map);
The implementation will be something like this:
public class MapUtils { public static <K, V> Map<K, V> asMap(Dictionary<K, V> dict) { return new AbstractMap<K, V>() { @Override public Set<Entry<K, V>> entrySet() { return new AbstractSet<Entry<K, V>>() { @Override public Iterator<Entry<K, V>> iterator() { return new Iterator<Entry<K, V>>() { private Enumeration<K> keys = dict.keys(); private Enumeration<V> elements = dict.elements(); private K k = null; @Override public boolean hasNext() { return keys.hasMoreElements(); } @Override public Entry<K, V> next() { k = keys.nextElement(); return new SimpleEntry<>(k, elements.nextElement()); } @Override public void remove() { if (k == null) { throw new IllegalStateException(); } dict.remove(k); k = null; } }; } @Override public int size() { return dict.size(); } }; } @Override public int size() { return dict.size(); } @Override public boolean containsKey(Object key) { return dict.get(key) != null; } @Override public V get(Object key) { return dict.get(key); } @Override public V put(K key, V value) { return dict.put(key, value); } @Override public V remove(Object key) { return dict.remove(key); } }; } }
Some overridden methods are optional, but I implemented them for performance reasons.
source share