ravthiru
ravthiru

Reputation: 9633

how to store file structure kind of data for easy retrieval and insertion

I want to store data in hierarchical format like /a/b/c.

Insertion operations are

insert /a/b/c/d1 20 (where 20 is size of d1) insert /a/b/c/d2 30 (where 30 is size of d2) insert /a/b/c 50 (where 50 is size of c itself) insert /a/b/x 40 (where 40 is size of x)

Retrieval operations are

Get size of /a/b/c should return 100 (20+30+50). Get Size of /a/b should return 140 (20+30+50+40 size of all children)

It will better if it can be implemented in java

Upvotes: 2

Views: 166

Answers (1)

Thomas Mueller
Thomas Mueller

Reputation: 50107

You could use a HashMap, as follows:

public class Test {
    public static void main(String... args) {
        HashMap<String, Integer> map = new HashMap<String, Integer>();
        put(map, "/a/b/c/d1", 20);
        put(map, "/a/b/c/d2", 30);
        put(map, "/a/b/c", 50);
        put(map, "/a/b/x", 40);
        System.out.println("/a/b/c: " + map.get("/a/b/c"));
        System.out.println("/a/b: " + map.get("/a/b"));
    }
    static void put(HashMap<String, Integer> map, String path, int value) {
        String p = "";
        for(String e : path.split("/")) {
            if (e.length() > 0) {
                p += "/" + e;
                Integer old = map.get(p);
                map.put(p, (old == null ? 0 : old) + value);
            }
        }
    }
}

Upvotes: 2

Related Questions