Kotlin List.contains() – Examples

Kotlin List.contains()

The Kotlin List.contains() function checks if the specified element is present in the list.

Syntax

List.contains(element)

Example 1

In this example,

  1. Take a list of strings.
  2. Take a string in a val, element.
  3. Call contains() function on this list, with the element passed as argument. If the element is present, then the function should return true.

Program

fun main(args: Array<String>) {
    val list1 = listOf("a", "b", "v", "k", "m")
    val element = "k"
    val result = list1.contains(element)
    print(result)
}

Output

true

Example 2

In this example,

  1. Take a list of strings.
  2. Take a string in a val, element. Let us take a value for element, such that it is not present in the list.
  3. Call contains() function on this list, with the element passed as argument. As the element is not present in the list, the function should return false.

Program

fun main(args: Array<String>) {
    val list1 = listOf("a", "b", "v", "k", "m")
    val element = "p"
    val result = list1.contains(element)
    print(result)
}

Output

false