1

I need to create a data structure in java which can represents hierarchy of data. Example use case is shown in the image below.

an organization hierarchy

In my case only the leaves level will have data, and the internal nodes should act like indexes. I should be able to get data from the data structure using multiple keys(Composite keys).

Is it okay to use nested maps, or should I implement an m way tree(B tree/B+ tree) for this use case.

3 Answers3

1

If the structure of the nested data is constant you could use normal classes with properties.

If the structure is dynamic I would use Maps, the interface and ignore the implementation.

About using using a custom tree structure, if you can use classes, thats better. If you use Maps, I would start with a HashMap and if you find it to be a problem your can replace your Map to something else later.

pirfalt
  • 11
  • 3
1

Obviously you have to use Tree like data structure. Here is the sample code of that.

High level code idea

class Entity{  
    // declare you attributes and below two properties

    List<Entity> children;

    boolean isleafNode;// for parent node its 'false' and for leaf node it will 'true'

    }
Jeet Kumar
  • 555
  • 3
  • 12
1

you can implement Trie for this use case. Iterate over composite key and return data if found.

class definition:

public class TrieNode {
    private HashMap<String, TrieNode> children;
    private Data data;
    private boolean isLeaf;

   // ...
}

find query will look like:

public Data find(List<String> compositeKey) {
    TrieNode current = root;
    for (String key: compositeKey) {
        TrieNode node = current.getChildren().get(key);
        if (node == null) {
            return null;
        }
        current = node;
    }
    if(current.isLeaf()) {
       return current.getData();
    } else {
       return null;
    }         
}

insert will look like:

public void insert(List<String> compositeKey, Data data) {
    TrieNode current = root;

    for (String key: compositeKey) {
        current = current.getChildren()
          .computeIfAbsent(key, c -> new TrieNode());
    }
    current.setLeaf(true);
    current.setData(data);
}
Mohd Waseem
  • 1,244
  • 2
  • 15
  • 36