'How can I get subList of a List in Apex Salesforce?

I have got a list of SObjects having N number of items/sObjects SObject[] sList = [sobject1, sboject2, sboject3, ........ , sobjectN]

How can I get just 10 items from the begining of the list

Thanks in advance!



Solution 1:[1]

After running this code newList contains only first 10 objects from sList.

SObject[] sList = [sobject1, sboject2, sboject3, ........ , sobjectN];
List<SObject> newList = new List<SObject>();
    for(Integer i = 0; i< 10;i++){
    newList.add(sList[i]);
}

For more info please reffer to List documentation

Solution 2:[2]

I also thought of using while and remove method:

SObject[] sList = [object1, object2,...];
if(sList.size() >= 10){
  while(sList.size() > 10){
    sList.remove(sList.size() - 1);
  }
}
System.debug('values: '+sList);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Moti Korets
Solution 2 Ernesto Valentin Caamal Peech