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 studentsval students = listOf("Steven", "Joseph", "Mary", "John")//check presence of an elementprint(students.contains("Mary"))}
Explanation
- Line 1: We define a function,
main(). Program execution starts from themain()function in Kotlin. Therefore, it is mandatory to define this. We write the rest of our code in themainfunction. - Line 3: We declare and initialize a list of students,
students. - Line 6: We check the presence of
Maryin the list of students,students, and return the boolean value. It returnstrueif the student is present. Otherwise, it returnsfalse.