0

I need to get the first 10 object from the list that comes from the Query without limiting in the query

notifs = [SELECT id FROM Notification__c 
                      WHERE Read__c=false ORDER BY Start__c DESC]; 

like in javascript i can use slice(0, 10),is there any way to get the sublist in APEX?

1

You can perform a regular for cycle iterating the first 10 results. Please be sure to validate that the list returns at least 10 results, otherwise you may run into a System.ListException: List index out of bounds exception.

Please find the example code for what you're trying to achieve:

List<Notification__c> notifs = [SELECT id FROM Notification__c WHERE Read__c=false ORDER BY Start__c DESC]; 

if(notifs.size()>=10){
    for(Integer i=0; i<=9; i++){
        System.debug(i + ': ' + notifs[i].Id);
    }
}

Best regards!

| improve this answer | |
  • thanks,it worked. but i found that there are no predefined method in APEX to get a sub list or slice the list – Arzad Apr 22 at 10:36
  • @Arzad That's correct. – sfdcfox Apr 22 at 11:29
  • 1
    Getting up to 10 is as easy as: while(!notifs.isEmpty() && otherList.size() < 10) { otherList.add(notifs.remove(notifs)); } or for(Integer i = 0, s = Math.min(10, otherList.size()), i < s; i++) { System.debug(notifs[i]); } – sfdcfox Apr 22 at 11:31

Not the answer you're looking for? Browse other questions tagged or ask your own question.