List.contains() method in Salesforce

3.7K    Asked by KanekoTakeda in Web-development , Asked on Jul 29, 2021
Is there any specific reason why salesforce did not provide list.contains() method.

Edit 1: The below methods are added to List class and are available after Spring 18 release to Sandboxes and Production instances. System.List Class) contains(listElement) Returns true if the list contains the specified element. ) indexOf(listElement)  Returns the index of the first  occurrence of the specified element in this list. If this list does not contain the element, returns -1.


Answered by Jack Russell

 Well, don’t know the official reason but why salesforce did not provide list.contains() method, but i guess, a few years ago, there's a quick one-liner you can use that's (relatively) faster than a straight loop, modified to be polymorphic:

Boolean listContains(Object[] source, Object target) { return (new Set(source)).contains(target); }
Example uses in executeAnonymous:
Account a = new Account(Name='Test'); Account[] aList = new Account[] { a }; System.assert(listContains(aList, a));
Integer[] values = new Integer[] { 1, 1, 2, 3, 5 }; System.assert(listContains(values, 3)); System.assert(!listContains(values, 7));


Your Answer

Answer (1)

In Salesforce Apex, the List.contains() method is used to check whether a list contains a specified element. Here's how it works:

Syntax:

Boolean contains(Object element)

Parameters:element: The element to check for in the list.

Return Value:

true if the list contains the specified element.

false otherwise.

Example:

List fruits = new List{'apple', 'banana', 'orange', 'grape'};
Boolean containsBanana = fruits.contains('banana'); 

System.debug(containsBanana); // Output: true In this example, the contains() method is used to check whether the fruits list contains the element 'banana'. Since 'banana' is present in the list, the method returns true, and the debug statement prints true.

You can use the contains() method with any type of list (List) in Salesforce Apex, including lists of primitive data types, custom objects, or SObjects.


7 Months

Interviews

Parent Categories