The contains() function of the Set class in Kotlin checks if the specified element is present in the set.
The syntax of Set.contains() function is:
abstract fun contains(element: E): Boolean
This contains() function of Set checks if the specified element is contained in this set.
Parameter | Optional/Required | Description |
---|---|---|
element | required | The element to be checked for presence in the set. |
Set.contains() returns value of type Boolean
.
In Kotlin, we can use the contains()
function to check if a set contains a specific element.
For example,
contains()
function to check if the set contains a specific element.println
function.fun main(args: Array<String>) {
val numbers = setOf(1, 2, 3, 4, 5)
val containsThree = numbers.contains(3)
println("Does the set contain 3? $containsThree")
}
Does the set contain 3? true
In Kotlin, we can use the contains()
function to check if an empty set contains a specific element.
For example,
contains()
function to check if the set contains a specific element.println
function.fun main(args: Array<String>) {
val emptySet = emptySet<String>()
val containsApple = emptySet.contains("apple")
println("Does the empty set contain 'apple'? $containsApple")
}
Does the empty set contain 'apple'? false
In Kotlin, the contains()
function can also be used with mutable sets to check for the presence of an element.
For example,
contains()
function to check if the set contains a specific element.println
function.fun main(args: Array<String>) {
val mutableSet = mutableSetOf("apple", "banana", "cherry")
mutableSet.add("date")
val containsBanana = mutableSet.contains("banana")
println("Does the mutable set contain 'banana'? $containsBanana")
}
Does the mutable set contain 'banana'? true
In this Kotlin tutorial, we learned about contains() function of Set: the syntax and few working examples with output and detailed explanation for each example.