NikonJR NikonJR -4 years ago 149
Java Question

How to Map Values to a Nested TreeMap

Nested TreeMap:

TreeMap<String,TreeMap<String,TreeMap<String,String>>> map = new TreeMap<>();

Trying to map things to the TreeMap:

map.put("1", ("1",("1","111")));

I am trying to map things to the nested TreeMap as seen above, but nothing I have tried has worked. What is the proper way to do what I am attempting?

Answer Source

You'll have to do it one step at a time, e.g. the simple case assuming all child maps already exist (note that we get the existing maps):

map.get("1").get("1").put("1", "111");

However, this isn't the case based on your description, and so each step of the way you'll have to create a new entry if one doesn't exist, so it becomes more complicated, as you have to look up the current map and then create/add:

// from your example:

String key1 = "1";
String key2 = "1";
String key3 = "1";
String value = "111";

// insert if doesn't exist yet:

TreeMap<String,TreeMap<String,String>> map1 = map.get(key1);

if (map1 == null) {
    map1 = new TreeMap<String,TreeMap<String,String>>();
    map.put(key1, map1);

// and again:

TreeMap<String,String> map2 = map1.get(key2);

if (map2 == null) {
    map2 = new TreeMap<String,String>();
    map1.put(key2, map2);

// and now we're set up and ready to go:

map2.put(key3, map3);

Since it's kind of cumbersome, it generally helps to write a utility function to do this for you.

Alternatively, if it is appropriate for your application, you could consider collapsing your entire structure into a single map and using a more complex key, for example:

static class ComplicatedKey implements Comparable<ComplicatedKey> {
    String key1;
    String key2;
    String key3;
    public ComplicatedKey (String key1, String key2, String key3) { ... }
    // implement equals and compareTo appropriately.


TreeMap<ComplicatedKey,String> map = ...;

map.put(new ComplicatedKey("1", "1", "1"), "111");

Yet another option is to roll your own multi-level tree, you could even use a TreeMap internally in each of your nodes to maintain lists of child nodes.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download