+ Start a Discussion

How to find if a particular value is in the list?

Is there anything like function "ListFind" in apex.


such that  ListFind(a,b) returns true or false depending on if  an element "b" is there in list "a" or not.


hi arosys..... you can find it by using SET...just check "contains" method in SETs ..add that list to a set. go for this link




set<string> myString = new Set<String>{'a', 'b'};
Boolean result;
result = myString.contains('z');
system.assertEquals(result, false);

I need to do it through lists only because later i will need its position also.



Well this is one of the problem that I generally face in!

So the workaround is having a Map(beacuse you need index else set can be used) and List Together.




have a look at following example[this will save couple of iterations that you will be doing to locate a particular value in list]


List<Account> accList = new List<Account>();
Map<String,Integer> accNameMap = new Map<String,Integer>();
Integer i =0;
for(Account acc : [SELECT Id,Name FROM Account Order By Name]){ accList.add(acc); accNameMap.put(acc.Name,i++); } //now you can directly check in set that if a particular account name exists or not by doing if(accNameMap.containsKey('MyAccount')){
//get the index
Integer index = accNameMap.get('MyAccount'); //do something if myaccount exists }

 PS : This will fail in case you have multiple account with same name, it will give you the index of the last one only



then you can try loop ...for example


//list of account

List<String> ListOfString;


//you want to find "xx" from ListOfString

//loop through the list

for(string str : ListOfString){


     //check for the value

     if(str ==  xx){

          //TODO Operation





Try something like

function boolean ListFind(List<String> a, String b){
    Set<String> tempSet = new Set<String>();
    return tempSet.contains(b);

 You just need to change List<String>, String and Set<String> to match your type requirements.


Hope this helps. 

Jamie 5mithJamie 5mith
As of Spring '18, you System.List.contains is vaild:
List<Account> accs = new List<Account>();

for(Account a : [SELECT Name FROM Account LIMIT 5]){