tags:

views:

53

answers:

2
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

+2  A: 

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"
    }
}
monorailkitty
You must be a visionary to answer THIS question.
furtelwart
"must be a visionary ..." I've seen worse requirements from customers! But looking at the title and behaviour of the example this certainly looks like what they were after.
vickirk
Perhaps you can use my code as an example to get you started?
monorailkitty
A: 

It sounds like you want a Trie-like structure. (Pronounce that "try", to avoid insanity.)

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

Kevin Bourrillion