Access an list from a list which stores all the list names

apexcollectioniterationlist

    List<string> lstStrng = new List<string>{'a','b'};
    List<string> lstOfNames = new List<string>{'lstStrng'};
    string name = lstOfNames[0];
    System.debug(name[0]);

I am Storing the Name of a list in another List. How to access lstStrng from lstOfNames? If i perform above operation, I am getting an error 'Method does not exist or incorrect signature: void add(String) from the type String'

Best Answer

This is where you should use a Map. By having a key, you can then dynamically retrieve the values i.e find me the list values of map entry called lstStrng.

Here is a broken down version of adding two entries to aMap<String, List<String>> (although I do not recommend keying by String for uniqueness reasons) and then finding the values of a dynamic String stored in a local variable i.e name as you have defined in your question.

Map<String, List<String>> myMap = new map<String, List<String>>();
List<String> lstStrngOne = new List<String>{'a','b'};
List<String> lstStrngTwo = new List<String>{'c','d'};
    
myMap.put('lstStrngOne', lstStrngOne);
myMap.put('lstStrngTwo', lstStrngTwo);

List<String> lstOfNames = new List<String>{'lstStrngOne'};
String name = lstOfNames[0];

System.debug(myMap.get(name));