0

We're using SOSL to search Account and Contact objects and facing an issue. Records are returned in a variable of type List<List<sobject>> say searchList

I'm using this variable(searchList), to find specifically just Account records using following code :

  Account[] searchAccounts =  (Account[])searchList[0];
                    for(Account a :searchAccounts ){
                         accountIdsIni.add(a.id);
                    }
 System.debug('AccountIdsInitial='+accountIdsIni );

Now I print both searchList and searchAccounts variables. I'm finding Account records are returned in different order(sort) as shown below: enter image description here

If you see, record(as highlighted in yellow) in debug log come first in SOSL variable but same record came on 4th number, when I separately printed the list of Accounts listed.

Please suggest if this is an expected behavior !!

  • 6
    What is the type of accountIdsIni? – David Reed Oct 7 '19 at 15:18
1

I'm assuming based on the observed behavior that accountIdsIni is typed as a Set<Id>. A Set is

an unordered collection of elements

The iteration order of a set

is deterministic, so you can rely on the order being the same in each subsequent execution of the same code.

but that doesn't mean that it's defined to be any specific order, or that the order of elements printed by System.debug() is guaranteed to be the same as the iteration order.

If you want an ordered collection, use a List.

  • Thanks David. 'accountIdsIni' is of type Account[] as shown in above code snippet . Let me try with list and revert.. thanks again !! – curious_techy Oct 8 '19 at 8:01
  • @curious_techy I think something is confused here. You're adding values of type Id to accountIdsIni, so it can't be of type Account[]. – David Reed Oct 8 '19 at 15:28
  • Good Catch. Sorry. accountIdsIni is of type Set and that was causing problem. Once i change it to 'List'. things worked fine. Thanks for your excellent support!! – curious_techy Oct 8 '19 at 16:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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