Kotlin Set - Contains() Function



The Kotlin set contains() function is used to check whether the specified element is present in the set. It returns true if the set element is equal to the argument of this function.

Here, are some use cases of the contains():

  • Verifying element in a set.
  • Checking subset relationship.
  • Conditional execution based on presence.

Syntax

Following is the syntax of Kotlin Set contains() function −

Set.contains(element: T)

Parameters

This function accepts as a parameter an element that needs to be checked.

Return value

This function returns true if an element is found in the set. Otherwise, return false.

Example 1: Checking Element Presence in a Set.

Let's see a basic example of the contains() function to verify if an element exists in a set.

fun main(args: Array<String>) {
   val flowers = setOf("Daisy", "Lotus", "Rose")
   println(flowers.contains("Lotus"))
   println(flowers.contains("Daisy"))
   println(flowers.contains("Lily"))
}

Output

Following is the output −

true
true
false

Example 2: Validating User Input

The following example uses the contains() function to validate the user input −

fun main(args: Array<String>) {
   val options = setOf("Yes", "No", "Maybe")
   val userInput = "Yes"
   if (options.contains(userInput)) {
      println("Valid input")
   } else {
      println("Invalid input")
   }
}

Output

Following is the output −

Valid input

Example 3: Checking Subset Relationship

This is another example of contains() function. Here, we verify if all elements of one collection exist in another −

fun main(args: Array<String>) {
   val set_1 = setOf(1, 2)
   val set_2 = setOf(1, 2, 3, 4)
   print("All element of set_1 available in set_2: ")
   if(set_1.all {set_2.contains(it)}){
       print("yes")
   } else {
       print("No")
   }
}

Output

Following is the output −

All element of set_1 available in set_2: yes
kotlin_sets.htm
Advertisements