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.
list.contains("element")
In this example, we check whether or not a student named Mary
is present in the list of students.
fun main(){//given list of studentsval students = listOf("Steven", "Joseph", "Mary", "John")//check presence of an elementprint(students.contains("Mary"))}
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.students
.Mary
in the list of students, students
, and return the boolean value. It returns true
if the student is present. Otherwise, it returns false
.