Kotlin Set contains()
Syntax & Examples


Set.contains() function

The contains() function of the Set class in Kotlin checks if the specified element is present in the set.


Syntax of Set.contains()

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.

Parameters

ParameterOptional/RequiredDescription
elementrequiredThe element to be checked for presence in the set.

Return Type

Set.contains() returns value of type Boolean.



✐ Examples

1 Using contains() to check for an element in the set

In Kotlin, we can use the contains() function to check if a set contains a specific element.

For example,

  1. Create a set of integers.
  2. Use the contains() function to check if the set contains a specific element.
  3. Print the result to the console using the println function.

Kotlin Program

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")
}

Output

Does the set contain 3? true

2 Using contains() with an empty set

In Kotlin, we can use the contains() function to check if an empty set contains a specific element.

For example,

  1. Create an empty set of strings.
  2. Use the contains() function to check if the set contains a specific element.
  3. Print the result to the console using the println function.

Kotlin Program

fun main(args: Array<String>) {
    val emptySet = emptySet<String>()
    val containsApple = emptySet.contains("apple")
    println("Does the empty set contain 'apple'? $containsApple")
}

Output

Does the empty set contain 'apple'? false

3 Using contains() with a mutable set

In Kotlin, the contains() function can also be used with mutable sets to check for the presence of an element.

For example,

  1. Create a mutable set of strings.
  2. Add elements to the set.
  3. Use the contains() function to check if the set contains a specific element.
  4. Print the result to the console using the println function.

Kotlin Program

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")
}

Output

Does the mutable set contain 'banana'? true

Summary

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.