-1

I have two lists List list1 = {a,b,c}; List list2 = {d,e,f};

I need to combine both of them into a List<List>, so that when I try to access combinedList[0][0] - display 'a' combinedList[0][1] - display 'd'

If I directly use the add method to combine the list I get {a,b,c,d,e,f}

Can any one help on this one please?

2 Answers 2

0

Given:

 String[] list1 = new String[] { 'a','b','c' };
 String[] list2 = new String[] [ 'd','e','f' };

If you wanted it so that [0][0] was 'a' and [1][0] was 'd' (I kind of think this is what you meant, you can:

List<List<String>> list3 = new List<List<String>> {
  list1, list2
};
// Output: [ [a,b,c], [d,e,f] ]

If you truly meant that you wanted it the other way around, such that the final dimensions would be [3x2], rather than the above, which would be [2x3], you do need to use a loop:

List<List<String>> list3 = new List<List<String>>();
for(Integer i = 0; i < list1.size(); i++) {
  list3.add(new String[] { list1[i], list2[i] });
}
// Output: [ [a,d], [b,e], [c,f] ]

If you have an indeterminate number of lists, you'd need a nested loop. This also presumes no error checking.

1
  • The for loop solution worked, getting the expected output. Thank you for the quick response.
    – Rohit
    Commented Feb 19, 2021 at 7:25
0

Please check the code below:

List<String> l1 = new List<String>{'a','b','c'};
List<String> l2 = new List<String>{'d','e','f'};
List<List<String>> lists = new List<List<String>>();
lists.add(l1);
lists.add(l2);
System.debug(lists[0][0]);      // 'a'

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .