MapDictionaryAdapter.java
/***************************************************************************
Copyright 2012 Emily Estes
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
***************************************************************************/
package net.metanotion.util;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
/** Convert an instance of {@link java.util.Map} into an instance of {@link net.metanotion.util.Dictionary}.
@param <K> The type of keys indexing this map/dictionary.
@param <V> The type of values indexed by this map/dictionary.
*/
public final class MapDictionaryAdapter<K,V>
implements DictionaryMap<K,V>, DictionaryIndex<K,V>, MutableDictionary<K,V> { //, Iterable<Map.Entry<K,V>> {
private final Map<K,V> map;
/** Create an instance of a {@link net.metanotion.util.DictionaryMap} backed by the instance of {@link java.util.Map}.
@param map The map instance used to back this dictionary.
*/
public MapDictionaryAdapter(final Map<K,V> map) { this.map = map; }
@Override public V get(final K key) { return map.get(key); }
@Override public void put(final K key, final V value) { map.put(key, value); }
@Override public V remove(final K key) { return map.remove(key); }
// TO DO so checkstyle will flag this so I can reevaluate whether this was the correct choice.
// @Override public Iterator<Map.Entry<K,V>> iterator() { return map.entrySet().iterator(); }
@Override public Set<K> keySet() { return this.map.keySet(); }
@Override public Map<K,Object> flattenWithList(final Map<K,Object> outmap) {
for(final Map.Entry<K,V> e: map.entrySet()) {
final Object v = outmap.get(e.getKey());
if(v == null) {
outmap.put(e.getKey(), e.getValue());
} else if(v instanceof List) {
((List) v).add(e.getValue());
} else {
final LinkedList list = new LinkedList();
list.add(v);
list.add(e.getValue());
outmap.put(e.getKey(), list);
}
}
return outmap;
}
}