How to check the presence of an element in a Kotlin collection

Overview

In Kotlin, a list is an ordered collection of elements. In this shot, we will learn to check whether or not an element is present in the collection/list.

Kotlin provides the contains() method on the list. This accepts an element as a parameter and returns a boolean value.

Syntax

list.contains("element")

Example

In this example, we check whether or not a student named Mary is present in the list of students.

Code

fun main(){
//given list of students
val students = listOf("Steven", "Joseph", "Mary", "John")
//check presence of an element
print(students.contains("Mary"))
}

Explanation

  • Line 1: We define a function, main(). Program execution starts from the main() function in Kotlin. Therefore, it is mandatory to define this. We write the rest of our code in the main function.
  • Line 3: We declare and initialize a list of students, students.
  • Line 6: We check the presence of Mary in the list of students, students, and return the boolean value. It returns true if the student is present. Otherwise, it returns false.

Free Resources