function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Firas Taamallah 18Firas Taamallah 18 

How to get only 3 first string from list of string using Apex?

Hello ,

Example : List<String> contain :  'A' ,'B' , 'C' , 'D' , 'E' 
I want to store in another list only 'A' and 'B' - how to achieve this?
Suraj Tripathi 47Suraj Tripathi 47

Hi Firas,

Please use the below function getSublist : 


public Static List<String> getSublist(List<String> oldStringList, Integer limit){
List<String> newStringList = new List<String>(); 
for(Integer i = 0; i < oldStringList.size(); i++){
 if(i < limit){ 
     newStringList.add(oldStringList[i]); 
 } 
} 
System.debug('oldStringList: '+ oldStringList); 
System.debug('newStringList : '+ newStringList);
return newStringList ;
}

In Execute Anonymous try: 

List<String> oldStringList = new List<String>();
oldStringList.add('a');
oldStringList.add('b');
oldStringList.add('c');
oldStringList.add('d');
oldStringList.add('e');
oldStringList.add('f');

System.debug('newStringList : '+ getSublist(oldStringList ,2));


User-added image
If this answer resolves your issue, please mark it as the best answer. 

Thank you.