ShowAll Questionssorted byDate Posted
Max Paq

# Calculations on a list

Hello everyone,

I am trying to do some data manipulation over records in a list. I was able to correctly build my list but now I am stuck with the calculations that I want to see happen.

Let's say I have record 1 and record 2 in my list. I want to grab a field called meter readings on both record and subtract the value of record 2 from the value from record 1 to get the actual energy use.

record 1 energy use = record 1 meter reading - record 2 meter reading.

And obvisouly I would like to repeat that for every records in my list except for the last one (since I would not have a second meter reading to do the calculation).

At first I thought of using a variable to control the for loop but I keep getting the following error message: "System.ListException: List index out of bounds: 15"

Here is the part of the code that is causing me trouble
```List<Item__c> currentItemList = meterToItemMap.get(currentMeter);

For( Integer i =0; i <currentItemList.size(); i++){
if(currentItemList.size()>1){
}
}```
I am quite new to APEX and coding so any help is welcome.
Thank you

Best Answer chosen by Max Paq
Ashlekh
Hi,

I went through the and found the you try to access a  record ahead.

The error is coming becuase when your code try access 14 record in list when you on that time it also try to access 15 record but your list has only 14 records.

```List<Item__c> currentItemList = meterToItemMap.get(currentMeter);

if(currentItemList ! = null && currentItemList.size()>)
{
For( Integer i =0; i <currentItemList.size(); i++)
{
Integer x = i+1;
if(currentItemList.size()> x){
}
}```

NaveenReddy
Hi,

Change for loop to below and try.

For( Integer i =0; i <currentItemList.size()-1; i++)

The actual problem is suppose  if you have 15 records, you are trying to accessing currentItemList[15].

Index starts from 0 and ends with 14. There is no record for index 15.

Regards,
Naveen
SSE , Salesforce CI expert group
http://www.autorabit.com"
Ashlekh
Hi,

I went through the and found the you try to access a  record ahead.

The error is coming becuase when your code try access 14 record in list when you on that time it also try to access 15 record but your list has only 14 records.

```List<Item__c> currentItemList = meterToItemMap.get(currentMeter);

if(currentItemList ! = null && currentItemList.size()>)
{
For( Integer i =0; i <currentItemList.size(); i++)
{
Integer x = i+1;
if(currentItemList.size()> x){