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
arosysarosys 

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.

Abhi_TripathiAbhi_Tripathi

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

 

http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_methods_system_set.htm

 

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

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

Avidev9Avidev9

Arosys,

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

 

Abhi_TripathiAbhi_Tripathi

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

     }

}

 

SeAlVaSeAlVa

Try something like

function boolean ListFind(List<String> a, String b){
    Set<String> tempSet = new Set<String>();
    tempSet.addAll(a);
    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]){

    if(!accs.contains(d)){
        accs.add(a);    
    }
}

https://releasenotes.docs.salesforce.com/en-us/spring18/release-notes/rn_apex_new_classes_methods.htm#rn_apex_new_classes_methods