Learn from industry experts! Admin batch starts from 19 Feb.
Hurry up!
Book your slot now!

3

Nested Lists in APEX

Nested Lists in Apex are lists that contain other lists as their elements. This data structure allows for the representation of multi-dimensional arrays or more complex data relationships within Salesforce Apex code.

What are Nested Lists in Apex?

Nested Lists in Apex are essentially lists of lists. They are useful for organizing data in a hierarchical or multi-dimensional structure. For instance, you might use a nested list to represent a matrix or a list of records where each record has multiple related items.

Nested Lists in Apex can be multidimensional also:

2-Dimensional

List<List<Datatype>> nestList = new List<List<Datatype>>();

3-Dimensional

List<List<List<Datatype>>> nestList = new List<List<List<Datatype>>>();

How to Use Nested Lists in Apex?

Using nested lists in Apex involves creating a list where each element is itself a list. Here are the basic steps:

  1. Declare the nested list: You need to declare a list of lists, specifying the data type of the inner lists.
  2. Initialize the nested list: Initialize the outer list and the inner lists.
  3. Add elements to the nested list: Populate the inner lists with elements and then add these inner lists to the outer list. There can be multiple ways to add elements in multi-dimensional list.

Nested Lists in Apex Example

Here is an example demonstrating how to use nested lists in Apex:

List<List<Integer>> nestedList = new List<List<Integer>>();
// Initialize inner lists
List<Integer> firstInnerList = new List<Integer>{1, 2, 3};
List<Integer> secondInnerList = new List<Integer>{4, 5, 6};
List<Integer> thirdInnerList = new List<Integer>{7, 8, 9};

// Add inner lists to the outer list
nestedList.add(firstInnerList);
nestedList.add(secondInnerList);
nestedList.add(thirdInnerList);

// Accessing elements from the nested list
Integer value = nestedList[1][2]; // This will retrieve the value 6 from the second inner list
System.debug(value); // Outputs: 6

// Iterating through the nested list
for (List<Integer> innerList : nestedList) {
    for (Integer num : innerList) {
        System.debug(num);
    }
}
salesforce-developer
Next Topic

Need more support?

Get a head start with our FREE study notes!

Learn more and get all the answers you need at zero cost. Improve your skills using our detailed notes prepared by industry experts to help you excel.

Book A 15-Minutes Free Career Counselling Today!