In this tutorial, you shall learn how to check if a specific element is present in a given Set in Kotlin using Set.contains() method, with examples.

Kotlin – Check if specific Element is present in Set

To check if specific element is present in given Set, call contains() function on this Set and pass the element to it. contains() function returns a boolean value of true: if the element is present in the Set; or false: if the element is not present in the Set.

The syntax to call contains() function to check if element is present in given Set mySet is

mySet.contains(element)

The Set must be initialized before we call contains() function on this Set.

Examples

ADVERTISEMENT

1. Check if element 16 is present in the set

In the following program, we will take a Set with some integer values, and check if the element 16 is present in this Set.

Since Set.contains() returns boolean value, we can use this as a condition in if statement.

Main.kt

fun main(args: Array<String>) {
    val mySet = setOf(1, 4, 9, 16, 25)
    val element = 16
    if (mySet.contains(element)) {
        println("The Set contains given element.")
    } else {
        println("The Set does not contain given element.")
    }
}

Output

The Set contains given element.

2. Check if element 36 is present in the set

In the following example, we will test the scenario where the element is not present in the Set.

Main.kt

fun main(args: Array<String>) {
    val mySet = setOf(1, 4, 9, 16, 25)
    val element = 36
    if (mySet.contains(element)) {
        println("The Set contains given element.")
    } else {
        println("The Set does not contain given element.")
    }
}

Output

The Set does not contain given element.

Conclusion

In this Kotlin Tutorial, we learned how to check if given element is present in this Set, using Set.contains() function, with the help of examples.