i want to create a hashmap from a hashmap with innermap and outermap relationship?
public interface InnerMap<V> extends Map<String, V> {
Map<String, V> getInnerMap(String prefix);
}
For exa开发者_如何学编程mple:
baseMap.put("aabb", "one");
baseMap.put("aabbddd", "two");
InnerMap map1 = baseMap.getInnerMap("aa");
map1.get("bb") => "one"
map1.get("bbdd") => "two"
map1.get("aa") => null
map2 = map1.getInnerMap("bb");
map2.get("dd") => "two"
and also want to override put and get method
It would be hard to keep track of all possible inner maps. There is no doubt a much more efficient solution than mine if you indexed keys and such like. However, if quick and dirty works for you, try this. You didn't mention a language so you're getting Java - hope I guessed right!
import java.util.HashMap;
import java.util.Map.Entry;
public class InnerMap extends HashMap<String, String> {
public InnerMap getInnerMap(String key) {
InnerMap innerMap = new InnerMap();
for (Entry<String, String> entry : entrySet()) {
String existingKey = entry.getKey();
String value = entry.getValue();
if (existingKey.startsWith(key)) {
String newKey = existingKey.substring(key.length());
innerMap.put(newKey, value);
}
}
return innerMap;
}
}
public class Test {
public static void main(String[] args) {
InnerMap baseMap = new InnerMap();
baseMap.put("aabb", "one");
baseMap.put("aabbdd", "two");
InnerMap map1 = baseMap.getInnerMap("aa");
System.out.println(map1.get("bb"));// => "one"
System.out.println(map1.get("bbdd"));// => "two"
System.out.println(map1.get("aa"));// => null
InnerMap map2 = map1.getInnerMap("bb");
System.out.println(map2.get("dd"));// => "two"
}
}
It sounds like you want a Trie-like structure. (Pronounce that "try", to avoid insanity.)
http://code.google.com/p/patricia-trie/
精彩评论