我想从hashmap创建一个hashmap与innermap和outermap关系?

时间:2009-11-19 13:55:58

标签: java hashmap

public interface InnerMap<V> extends Map<String, V> {
    Map<String, V> getInnerMap(String prefix);
}

例如:

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"

并且还想覆盖put和get方法

2 个答案:

答案 0 :(得分:2)

很难跟踪所有可能的内部地图。毫无疑问,如果你索引键等等,那么解决方案比我的解决方案更有效。但是,如果快速和脏污适合您,请尝试此操作。你没有提到一种语言,所以你得到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"
    }
}

答案 1 :(得分:0)

听起来你想要一个类似Trie的结构。 (发音为“尝试”,以避免精神错乱。)

http://code.google.com/p/patricia-trie/