Detailed Guide to Contains Method in Salesforce Apex

Detailed Guide to Contains Method in Salesforce Apex

On May 23, 2024, Posted by , In Salesforce Apex Tutorial, With Comments Off on Detailed Guide to Contains Method in Salesforce Apex
Contains Method in Salesforce Apex
Contains Method in Salesforce Apex

Table of Contents

Introduction

The contains method provides developers with a versatile mechanism to perform containment checks across different data structures in Salesforce Apex. Whether it’s confirming the existence of elements in Lists and Sets, searching for substrings within Strings, or validating keys in Maps, the contains method empowers developers to efficiently manage and manipulate data.

Check out these top Salesforce interview questions and answers for extensive knowledge and informative details about Salesforce Admin, Developer, Integration, and LWC modules.

By leveraging the contains method, developers can streamline their code logic, enhance data validation processes, and ensure the integrity of their Salesforce applications. Its flexibility and ease of use make it a valuable tool for a wide range of use cases, from basic data checks to more intricate data processing operations.

Syntax and Usage

The syntax of the contains method varies slightly depending on the data type of the collection being evaluated:

For Lists and Sets:

The contains method in Salesforce Apex is utilized with Lists and Sets to ascertain whether a specific element exists within the collection. It evaluates the presence of the element based on its value and returns a Boolean result indicating its existence.

Read more: Arrays in Salesforce Apex

Boolean result = listOrSet.contains(value);
  • listOrSet : The List or Set in which the containment check is performed.
  • value : The element being checked for existence within the List or Set.
  • result : A Boolean variable that indicates whether the List or Set contains the specified value. It will be true if the value is found, otherwise false .

For Strings:

When applied to Strings, the contains method checks for the occurrence of a specified substring within the String. It searches for the substring and returns true if it is found within the String, otherwise false .

Checkout: DML statements in Salesforce

Boolean result = map.containsKey(key);
  • string : The String in which the substring containment check is performed.
  • substring : The substring being searched for within the String.
  • result : A Boolean variable that indicates whether the substring exists within the String. It will be true if the substring is found, otherwise false .

For Maps:

In the context of Maps, the contains method is used to verify whether the Map contains a particular key. It examines the keys of the Map and returns true if the specified key is present, indicating that the Map contains a mapping for that key. Otherwise, it returns false .

String str = 'Hello, world!';
Boolean containsHello = str.contains('Hello'); // true
Boolean containsGoodbye = str.contains('Goodbye'); // false
  • map : The Map in which the key containment check is performed.
  • key : The key being checked for existence within the Map.
  • result : A Boolean variable that indicates whether the Map contains the specified key. It will be true if the key is present in the Map, indicating that the Map contains a mapping for that key. Otherwise, it will be false .

Basic Usage:

The contains method is commonly used to determine whether a String contains a particular substring. For example:

Checking for Element Existence in a List or Set

In Lists and Sets, the contains method verifies whether a specific element exists within the collection. Here’s a simple example:

List<Integer> numbers = new List<Integer>{1, 2, 3, 4, 5};
Boolean containsThree = numbers.contains(3); // true
Boolean containsTen = numbers.contains(10); // false

Using Contains with Maps

In Maps, the containsKey method serves a similar purpose to contains for Lists and Sets. It checks whether a Map contains a specific key.

Readmore: Record Types in Salesforce

Example:

Map<String, Integer> salesByQuarter = new Map<String, Integer>{
    'Q1' => 10000,
    'Q2' => 12000,
    'Q3' => 11000,
    'Q4' => 10500
};
Boolean containsQ3 = salesByQuarter.containsKey('Q3'); // true
Boolean containsQ5 = salesByQuarter.containsKey('Q5'); // false

Handling Complex Scenarios:

Checking for Object Existence in a List

The contains method can also be used to check for object existence in a list of custom objects.

For instance:

// Custom object definition
public class CustomObject {
    public String name;
    public Integer value;
    public CustomObject(String n, Integer v) {
        name = n;
        value = v;
    }
}

// List of custom objects
List<CustomObject> customObjects = new List<CustomObject>{
    new CustomObject('A', 1),
    new CustomObject('B', 2),
    new CustomObject('C', 3)
};

// Check if a specific CustomObject exists in the list
Boolean containsB = customObjects.contains(new CustomObject('B', 2)); // true
  1. Custom Object Definition: The code defines a custom Apex class named CustomObject with two public properties: name (String) and value (Integer). It also includes a constructor to initialize these properties when creating instances of the class.
  2. List Initialization: A list named customObjects of type CustomObject is initialized with three instances of the CustomObject class. Each instance is created using the constructor with specific values for name and value .
  3. Object Existence Check: The contains method is used to check if a specific instance of CustomObject exists in the customObjects list. This method compares objects for equality based on their properties.
  4. Comparison Logic: In the object existence check, a new instance of CustomObject with name ‘B’ and value 2 is created. The contains method compares this object with each element in the list to determine if an equivalent object exists.
  5. Result Assignment: The result of the object existence check is assigned to the Boolean variable containsB . It will be true if the specified CustomObject exists in the list, indicating that an object with the same name and value was found. Otherwise, it will be false , indicating that such an object does not exist in the list.

Read more about formula fields in Salesforce. This tutorial covers everything you need to know to master formula fields and enhance your Salesforce expertise.

Scenario-based examples

Checking for Substring Presence in a List of Strings:

List<String> names = new List<String>{'Alice', 'Bob', 'Charlie', 'David'};
Boolean containsAlice = names.contains('Alice'); // true
Boolean containsEve = names.contains('Eve'); // false
  • In this example, we have a list of strings called names .
  • We use the contains method to check if the list contains the string 'Alice' .
  • The result will be true if the list contains the string 'Alice' , otherwise false .

Read more: Roles in Salesforce

Verifying Case-Insensitive String Containment:

String sentence = 'The quick brown fox jumps over the lazy dog';
Boolean containsDog = sentence.toLowerCase().contains('dog'); // true
  • We have a string sentence containing a sentence.
  • We convert sentence to lowercase using the toLowerCase() method before applying the contains method.
  • This ensures that the check for the presence of the substring 'dog' is case-insensitive.

Searching for Multiple Values in a Set:

Set<String> fruits = new Set<String>{'apple', 'banana', 'orange'};
Boolean containsAppleOrBanana = fruits.contains('apple') || fruits.contains('banana'); // true
  • Here, we have a set of strings called fruits .
  • We use the logical OR ( || ) operator to check if the set contains either 'apple' or 'banana' .
  • The result will be true if the set contains either of these values.

Checking for Nested List Containment:

List<List<Integer>> nestedLists = new List<List<Integer>>{{1, 2}, {3, 4}, {5, 6}};
List<Integer> sublist = new List<Integer>{3, 4};
Boolean containsSublist = nestedLists.contains(sublist); // true
  • We have a list of lists of integers called nestedLists .
  • We create a sublist containing integers {3, 4} .
  • We use the contains method to check if the nestedLists contains this sublist.
  • The result will be true if nestedLists contains the sublist {3, 4} .

Validating Key Presence in a Map of Lists:

Map<String, List<String>> fruitCategories = new Map<String, List<String>>{
    'Red' => new List<String>{'apple', 'cherry', 'strawberry'},
    'Yellow' => new List<String>{'banana', 'lemon'},
    'Orange' => new List<String>{'orange', 'peach'}
};
Boolean containsRedCategory = fruitCategories.containsKey('Red'); // true
  • We have a map called fruitCategories where keys represent fruit categories (e.g., ‘Red’, ‘Yellow’) and values are lists of fruits.
  • We use the containsKey method to check if the map contains the key 'Red' .
  • The result will be true if the map contains the key 'Red' , indicating the presence of the corresponding list of fruits.

Are you eager to dive into the exciting world of Salesforce? Ready to elevate your skills and become a Salesforce aficionado? At CRS Info Solutions, we provide dynamic and 100% practical Salesforce training in Hyderabad that ignites your passion for learning. Our courses offer daily notes, interview preparation, resume assistance, 100% job placement assistance guidance and certification guidance, ensuring you’re fully equipped for success. Don’t hesitate – enroll for a free demo today and begin your Salesforce journey with us!

Banking Application Examples

1. Checking if a Transaction Description Contains a Specific Keyword

In a banking application, you might need to check if a transaction description contains specific keywords such as “payment”, “transfer”, or “fee”.

Read more: Types of relationships in Salesforce

public class Transaction {
    private String description;

    public Transaction(String description) {
        this.description = description;
    }

    public boolean containsKeyword(String keyword) {
        return description.toLowerCase().contains(keyword.toLowerCase());
    }

    public static void main(String[] args) {
        Transaction transaction = new Transaction("Monthly Payment to Credit Card");
        System.out.println(transaction.containsKeyword("payment")); // Output: true
    }
}

2. Verifying if a Customer’s Email Contains a Specific Domain

In customer management, you might want to check if a customer’s email belongs to a certain domain, such as “bank.com”.

public class Customer {
    private String email;

    public Customer(String email) {
        this.email = email;
    }

    public boolean isEmailFromDomain(String domain) {
        return email.toLowerCase().contains(domain.toLowerCase());
    }

    public static void main(String[] args) {
        Customer customer = new Customer("[email protected]");
        System.out.println(customer.isEmailFromDomain("bank.com")); // Output: true
    }
}

3. Checking if a List of Suspicious Activities Contains a Specific Activity

In fraud detection, you might need to check if a list of suspicious activities contains a specific type of activity, such as “large withdrawal”.

import java.util.ArrayList;
import java.util.List;

public class FraudDetection {
    private List<String> suspiciousActivities;

    public FraudDetection() {
        this.suspiciousActivities = new ArrayList<>();
    }

    public void addActivity(String activity) {
        suspiciousActivities.add(activity);
    }

    public boolean containsActivity(String activity) {
        return suspiciousActivities.stream().anyMatch(a -> a.toLowerCase().contains(activity.toLowerCase()));
    }

    public static void main(String[] args) {
        FraudDetection fraudDetection = new FraudDetection();
        fraudDetection.addActivity("Large Withdrawal at ATM");
        fraudDetection.addActivity("Multiple Failed Login Attempts");

        System.out.println(fraudDetection.containsActivity("large withdrawal")); // Output: true
    }
}

4. Verifying if an Account Number is in a List of Blacklisted Accounts

In compliance checks, you might need to verify if a given account number is in a list of blacklisted accounts.

import java.util.HashSet;
import java.util.Set;

public class ComplianceCheck {
    private Set<String> blacklistedAccounts;

    public ComplianceCheck() {
        this.blacklistedAccounts = new HashSet<>();
    }

    public void addBlacklistedAccount(String accountNumber) {
        blacklistedAccounts.add(accountNumber);
    }

    public boolean isAccountBlacklisted(String accountNumber) {
        return blacklistedAccounts.contains(accountNumber);
    }

    public static void main(String[] args) {
        ComplianceCheck complianceCheck = new ComplianceCheck();
        complianceCheck.addBlacklistedAccount("123456789");
        complianceCheck.addBlacklistedAccount("987654321");

        System.out.println(complianceCheck.isAccountBlacklisted("123456789")); // Output: true
    }
}
Comments are closed.