To check if a specific item is present in a Set in Kotlin, you can use the contains
method.
In this example,
mySet
containing elements of a specific type.contains
method of the Set to check if a specific item is present.contains
method returns true
if the item is present in the Set, otherwise it returns false
.fun main() {
// Define Set with items
val mySet = setOf("apple", "banana", "orange", "grape", "melon")
// Check if item is present
val item = "banana"
val isPresent = mySet.contains(item)
// Print result
println("Is $item present in the Set? $isPresent")
}
Is banana present in the Set? true
In this example,
mySet
containing elements of a specific type.contains
method of the Set to check if a specific item is not present.contains
method returns false
if the item is not present in the Set.fun main() {
// Define Set with items
val mySet = setOf("apple", "banana", "orange", "grape", "melon")
// Check if item is not present
val item = "peach"
val isNotPresent = !mySet.contains(item)
// Print result
println("Is $item not present in the Set? $isNotPresent")
}
Is peach not present in the Set? true
In this tutorial, we learned How to check if a Specific Item is present in the Set in Kotlin language with well detailed examples.