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
SUMAN KUMARI 70SUMAN KUMARI 70 

Why is my for loop executing only for the 1st item in the list

Hi All, 
I have an apex method where I hava  a for loop which is iterating over a list of items. That list has 2 items in it but the loop is returning only the 1st item. 
Can you guys please help me out with it and let me know where I am going wrong.
public static String getPrecission(String imageString){
        try{
            String modelIdValues = System.Label.quote_Id;
            if(!String.isBlank(quoteIdValues)){
                List<String> quoteIdLst = (quoteIdValues.contains(';')) ? quoteIdValues.split(';') : new List<String>{quoteIdValues};
                    
                if(quoteIdLst.size() > 0){
                    
                	String accessToken = getAccessToken();
                    
                    for(String quote: quoteIdLst){
                        
                        List<Vision.Precission> lstPricission = *****************;
                        
                        return JSON.serialize(lstPricission);
                    }
                }
            }
            return JSON.serialize(new List<Vision.Precission>());
        }catch(Exception e){
            System.debug(e.getMessage());
            return JSON.serialize(new List<Vision.Precission>());
        }
    }

Please do help me out, why for loop is iterating only for the 1st element of the list. 
Best Answer chosen by SUMAN KUMARI 70
RituSharmaRituSharma
lstPricission is declared inside the loop. Declare it outside the loop if you want to return outside the loop.

All Answers

Marc Porst 8Marc Porst 8

Hi Suman, 

It's because you return within the loop. 

 

for (Integer i = 0;i<10;i++){
    System.debug(i);
    return;
}

System.debug('READY');


Would print only 0.

 

Marc

SUMAN KUMARI 70SUMAN KUMARI 70
Hi Marc, 
But when I am trying to return outside the loop I was getting an error sayion "Variable does not exist: lstPricission". 
 
RituSharmaRituSharma
lstPricission is declared inside the loop. Declare it outside the loop if you want to return outside the loop.
This was selected as the best answer
SUMAN KUMARI 70SUMAN KUMARI 70
Thanks Ritu :)