Kotlin List contains()
Syntax & Examples
Syntax of List.contains()
The syntax of List.contains() function is:
abstract fun contains(element: E): Boolean
This contains() function of List checks if the specified element is contained in this collection.
✐ Examples
1 Example
In this example,
- We create a list named
list1
containing the characters'a', 'p', 'p', 'l', 'e'
. - We check if
list1
contains the element'p'
using the Listcontains()
function. - The result, which is a Boolean value indicating whether
'p'
is inlist1
, is stored incontainsP
. - Finally, we print the value of
containsP
to standard output using the print statement.
Kotlin Program
fun main(args: Array<String>) {
val list1 = listOf("a", "p", "p", "l", "e");
val containsP = list1.contains("p");
print(containsP);
}
Output
true
2 Example
In this example,
- We create a list named
list1
containing the integers10, 20, 30
. - We check if
list1
contains the element20
using the Listcontains()
function. - The result, which is a Boolean value indicating whether
20
is inlist1
, is stored incontains20
. - Finally, we print the value of
contains20
to standard output using the print statement.
Kotlin Program
fun main(args: Array<String>) {
val list1 = listOf(10, 20, 30);
val contains20 = list1.contains(20);
print(contains20);
}
Output
true
Summary
In this Kotlin tutorial, we learned about contains() function of List: the syntax and few working examples with output and detailed explanation for each example.