Ask a Question
Ask Question Login
Corporate Training
  1. Community
  2. Web-development
  3. Question
Web-development

List.contains() method in Salesforce

Asked by Kaneko Takeda Jul 29, 2021 5.2K views 2 answers
Share

About this question

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.


Your answer

2 Answers

Ranjana Admin JanBask Expert Latest answer

Answered on May 7, 2024

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.


Was this helpful?

More Web-development discussions

Learn & Explore

Free tutorials and interview questions from industry experts — learn the skill, then get ready to prove it.

Latest from the JanBask Blog

Guides, tips and career advice from JanBask experts.