0

I am trying to add a List of collection to a Map Collection with the same Index.

I have this Code:

List<Account> accountContactList = [SELECT Id,Name FROM Account];
Map<Integer,List<Account>> objWrapper = new Map<Integer,List<Account>>();
List<Account> listToMapCOllection = new List<Account>();
Integer viewPerPage = 5;
Integer counterIndex = 1;
Integer counterToViewPerPage  = 1;

        for(Account accCont: accountContactList){
            if(counterToViewPerPage <= viewPerPage){
                listToMapCOllection.add(accCont);
                counterToViewPerPage++;
            }else{
                objWrapper.put(counterIndex,listToMapCOllection);
                counterIndex++;
                counterToViewPerPage = 1;
                listToMapCOllection.clear();
            }
        }

Now my problem is when the result of accountContactList Collection is only 2 or the size of the collection is an ODD, the code will nerver go to else condition and it will not add to my Map Collection (objWrapper ). Any help please.

EDITED: In every loop of 5 the list of collection will add to the Map collection, So for the first 5 of loop of the list of the collection will add to map with the index of 1 and the second loop of five will add to Map with the index of 2.

1 Answer 1

0

If you want to keep this approach intact and make a minimal, simple change, add a condition after your loop to see if you have any elements in the collection.

for (Account record : collection)
{
    // current logic
}
if (!listToMapCollection.isEmpty())
{
    // add to map
}
2
  • I forgot to mention that in every loop of 5 the list of collection will add to the Map collection, So for the first 5 of loop of the list of the collection will add to map with the index of 1 and the second loop of five will add to Map with the index of 2. Commented Feb 12, 2019 at 4:01
  • Yeah you would just use the map.size() as the key for your put call.
    – Adrian Larson
    Commented Feb 12, 2019 at 4:20

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .