Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

kotlin
community creator

How to use the HashSet.isEmpty method in Kotlin

Programming Bytes

Overview

We can use the isEmpty() method to check if the HashSet object is empty (no elements present).

Syntax

fun isEmpty(): Boolean

Parameters

This method doesn’t take any argument.

Return value

This method returns true if the HashSet object is empty. Otherwise, false is returned.

Example

The code below demonstrates how to use the isEmpty() method:

fun main() {
  //create a new HashSet which can have integer type as elements
  var set: HashSet<Int> = hashSetOf<Int>()

  println("\nThe set is : $set")
  println("set.isEmpty :" + set.isEmpty());

  // add four entries
  set.add(1)
  set.add(2)
  set.add(3)
  set.add(4)
  
  println("\nThe set is : $set")
  println("set.isEmpty :" + set.isEmpty());
} 
Using the isEmpty method

Explanation

In the code above, we see the following:

  • Line 3: We create a new HashSet object with the name set. We use the hashSetOf() method to create an empty HashSet.

  • Line 6: We use the isEmpty() method to check if the set is empty. The set contains no elements so true is returned.

  • Lines 9–12: We add four new elements (1,2,3,4) to the set using the add() method.

  • Line 15: We use the isEmpty() method to check if the set is empty. The set contains four elements, so false is returned.

RELATED TAGS

kotlin
community creator
RELATED COURSES

View all Courses

Keep Exploring