Kotlin Set - isNotEmpty() Function



The Kotlin Set isNotEmpty() function is used to return the boolean value. True if the set is not empty means the set contains elements. False if the set does not contains any element.

There are the following use cases of the isNotEmpty() function:

  • Validation: It ensure that the set contains element before proceeding with operation that required non-empty set.
  • Conditional Logic: Execute different action based on whether a collection is empty or not.
  • User Notification: If the set is empty, it displays a message to users based on the availability of items, such as "No items found."

Syntax

Following is the syntax of Kotlin set isNotEmpty() function −

Set.isNotEmpty()

Parameters

This function does not accepts any parameters.

Return value

This function returns true if the set contains elements otherwise returns false.

Example 1: Checking Whether set is Empty or not

Let's see a basic example of the isNotEmpty() function, which returns true if the set is not empty.

fun main(args: Array<String>) {
   val set = setOf(1, 2, 3, 2);
   val isNotEmpty = set.isNotEmpty();
   if(isNotEmpty == true){
      println("set is not empty!: " + set)
   }else{
      println("set is empty!")
   }
}

Output

Following is the output −

set is not empty!: [1, 2, 3]

Example 2: Set Automatically Removes Duplicate

The following example combines isNotEmpty() with the other checks to simplify the logic −

fun main(args: Array<String>) {
   // set contains duplicate elements
   val number = setOf(10, 20, 30, 40, 10, 20)

   if (number.isNotEmpty()|| number.size>4) {
      println("Size of the number: ${number.size}")
      println("Set does not contains duplicate elements: ${number}")
   } else {
      println("Set is empty!")
   }
}

Output

Following is the output −

Size of the number: 4
Set does not contains duplicate elements: [10, 20, 30, 40]

Example 3: If the Set is Empty

This is another example of isNotEmpty() function if the set is empty, it return the false −

fun main(args: Array<String>) {
   val empty_set: Set<String> = setOf()
   val flag = false
   if (empty_set.isNotEmpty()) {
      println("set is not empty? " + flag)
   } else {
      println("set is empty? " + !flag)
   }
}

Output

Following is the output −

set is empty? true
kotlin_sets.htm
Advertisements