How deep can nested Maps go, and how do I properly add data to those nested maps?

There is a nested limit of 7 collections. If you attempt to go beyond this, you'll get an error:

Nested type exceeds maximum level: 8


First question: Is this even possible? Am I exceeding any limits with a Map like this? I have looked over documentation and can't find anything regarding nested map limits.

I know it's in the documentation[citation needed]†, but it's easy enough to test by using the following Execute Anonymous script:

Map<Id, Map<Id, Map<Id, Map<Id, Map<Id, Map<Id, Map<Id, Map<Id, Map<Id, Id>>>>>>>>> x;

However, assuming each role Id is unique, I don't see why you couldn't just use a simple:

Map<String, CustomRole> roles = new Map<String, CustomRole>();

Where CustomRole is just a class that stores the necessary data. To actually build the trees, perhaps in a Visualforce page, you still only need something like:

CustomRole[] roleTree = new CustomRole[0];

Where CustomRole would contain a list of children you could recursively iterate over. It'd probably be a lot easier to build the required functionality in JavaScript if that's an option.


Second question: Since I will be storing data incrementally in the map (as detailed above), I need to store data in the map as I get it, and continue to build the map as I go through the loops and make the calls. I've never dealt with a nested map before, especially not a 6-level-deep nested map. How would I properly insert data into the map for the second level while maintaining the third, fourth, fifth, and sixth levels as null, and then move on to storing data in the third level while keeping the fourth, fifth, and sixth null, and so on, until the map is complete?

If you really wanted to torture yourself with this logic, you simply need to keep track of which layer you're in. I'm not going to write this out explicitly, because just off the top of my head, it looks like you're going to be looking at the 100+ lines of code ballpark. This really isn't ideal when a simple recursive loop should be just fine. Starting with a simple Map<String, CustomRole> would be a lot easier to read and maintain.

† The documentation states there's actually a limit of four nested elements, for a total of five deep, but the prior limit is seven nested elements for a total of eight deep. Execute Anonymous currently honors the 8-level construct, but it seems that salesforce is planning on reducing it, either because nobody uses it, or for some other optimization.