+ Start a Discussion
TaruniTaruni 

Copy few list values to another list

Hi,

 

I was trying to copy some of the List values to another List.

eg: If List1 ={'A','B','C'}

then I want to copy only List[0] and List[2] values to another list "List2".

please help me with the code.

Best Answer chosen by Admin (Salesforce Developers) 
hitesh90hitesh90

Hi,

 

You have to make one change in your code.

see below code.

 

if(ListQA.size()>0)
    {
    SubListQA.add(ListQA[0]);
    }
    if(ListQA.size()>2)
    {
    SubListQA.add(ListQA[2]);
    }
    system.debug('SubListQA' +SubListQA);
    }   

 

 

Important :
Hit Kudos if this provides you with useful information and if this is what you where looking for then please mark it as a solution for other benefits.
 
Thank You,
Hitesh Patel
SFDC Certified Developer & Administrator

All Answers

hitesh90hitesh90

Hi Taruni,

 

You have to put if condition to check the size of the List1 to resolve the List index out of bound issue.

 

List<String> List1 = new List<String>{'A','B','C'};
List<String> List2 = new List<String>();
if(List1.size() > 0){
	List2.add(List1[0]);
}
if(List1.size() > 1){
	List2.add(List1[2]);
}

 

Important :
Hit Kudos if this provides you with useful information and if this is what you where looking for then please mark it as a solution for other benefits.

Thank You,
Hitesh Patel
SFDC Certified Developer & Administrator

Sri549Sri549

Yes Its helped me and my requirement  and Really great!!!

 

Thank you.

Srinivas

TaruniTaruni
if(ListQA.size()>0)
    {
    SubListQA.add(ListQA[0]);
    }
    if(ListQA.size()>1)
    {
    SubListQA.add(ListQA[2]);
    }
    system.debug('SubListQA' +SubListQA);
    }   

 

I was able to add List[0] to sublistQA but on UI for list[2], I am getting System.ListException: List index out of bounds: 2

hitesh90hitesh90

Hi,

 

You have to make one change in your code.

see below code.

 

if(ListQA.size()>0)
    {
    SubListQA.add(ListQA[0]);
    }
    if(ListQA.size()>2)
    {
    SubListQA.add(ListQA[2]);
    }
    system.debug('SubListQA' +SubListQA);
    }   

 

 

Important :
Hit Kudos if this provides you with useful information and if this is what you where looking for then please mark it as a solution for other benefits.
 
Thank You,
Hitesh Patel
SFDC Certified Developer & Administrator

This was selected as the best answer
TaruniTaruni
Thank you so much!