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
AdamHAdamH 

Finding index of element in List

I'm sure there is a simple answer to this, but I can't seem to find it. Is there not a method available to return an index position of a list item? I want to do something like this:

 

myList.remove(myList.indexOf('Some Value'));

 Is my only option to loop through myList comparing each element as I go?

Best Answer chosen by Admin (Salesforce Developers) 
Avidev9Avidev9

Adam,

Well since you are using List, duplicates value can stay in it hence indexOf in a list doesnt make sense.

 

But if opt to move to SETs there is a function call remove. That actually removes the value using the value itself.

 

 

 

All Answers

Devender MDevender M
Hi Adam,

for example list<string> listOFName = new list<string>();

listOFName.add('aaa');
listOFName.add('bbb');
listOFName.add('ccc');
listOFName.add('ddd');
listOFName.add('eee');
system.debug('listOFName before'+listOFName);
//suposse u want 2 remove a element ex : ccc

for(integer i=0; i<listOFName.size(); i++ ) {
if(listOFName[i] == 'ccc') {
listOFName.remove(i);
break;
}
}
system.debug('listOFName after'+listOFName);
Avidev9Avidev9

Adam,

Well since you are using List, duplicates value can stay in it hence indexOf in a list doesnt make sense.

 

But if opt to move to SETs there is a function call remove. That actually removes the value using the value itself.

 

 

 

This was selected as the best answer
AdamHAdamH

Thanks for the reply Devender, but I'm trying to stay away from loops if possible. If all else fails, I'll certainly use your suggestion.

 

 

Thanks again.

AdamHAdamH

Thank you Avidev9 for the help. I have replaced my Lists with Sets and all is well :-). Now, if there were just a join() method on Sets! Oh well, can't have your cake and eat it too I guess. I'll just have to loop the Set to add my delimiter.

 

Thanks again!

sfdcfoxsfdcfox

You can construct a list from a set using the List(Set) constructor. No need to loop.

 

Set<String> nameSet = new Set<String>();

...

String result = String.join(new List<String>(nameSet),', ');

Edit: I'll have some of that cake now.