Checking to see if a value is present in a list - Apex

  • As a part of my first trigger, which is running on Opportunities, I have a list I created that contains the result of a SOQL query. Here is the code.

    List<Custom_Object__c> mylist = [SELECT Id, Custom_Field_1__c FROM Custom_Object__c WHERE Custom_Field_2 = 'Value' AND Custom_Field__c > 0];

    I have a custom field on Opportunities and I want to see if it's value matches a value of Custom_Field_1__c from this list. I've spent a fair amount of time looking around but am still stumped. How do I do this?

  • Instead of using a list you could put the values of Custom_Field_1__c into a set.

    then when you do a compare you can use a method called contains.

    set<string> myset = new set<string>(); 
    For(Custom_Object__c m :mylist){ 
    for (Opportunity o: {
        myset.contains(o.Fieldvalue__c); //returns true/false

    I need to convert the SOQL results, a list of sobjects, to set of strings (the value of Custom_Field_1__c). Can this be done?

    You could iterate through your list of sobjects to populate the set. set myset = new set(); For(Custom_Object__c m :mylist){ myset.add(m.custom_field_1__c); } Then you can do MySet.contains('Comparison_String');

    Yo, Brian, I took the liberty of moving your code from the comment into the answer. I still don't have the rep to edit without peer review, so if someone wants to take a look, feel free to approve or reject. :-)

    This is exactly what I needed. Thank you so much to both of you!

    Peter - well that was a good idea:) Thank you for moving it.

License under CC-BY-SA with attribution

Content dated before 7/24/2021 11:53 AM

Tags used