[英]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 example: 例如:
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 并且还想覆盖put和get方法
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!
您没有提到一种语言,因此您正在使用Java-希望我猜对了!
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. 听起来您想要类似Trie的结构。 (Pronounce that "try", to avoid insanity.)
(请说“尝试”,以避免精神错乱。)
http://code.google.com/p/patricia-trie/ http://code.google.com/p/patricia-trie/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.