How do I check if a collection is empty or contains an element in Kotlin?

In Kotlin, use isEmpty() / isNotEmpty() to check whether a collection has elements, and use in, contains(), or map-specific methods to check contents.

val names = listOf("Alice", "Bob")

println(names.isEmpty())     // false
println(names.isNotEmpty())  // true

println("Alice" in names)    // true
println("Charlie" !in names) // true

For lists and sets:

val numbers = setOf(1, 2, 3)

if (numbers.isNotEmpty()) {
    println("The set has elements")
}

if (2 in numbers) {
    println("The set contains 2")
}

For maps, check keys or values explicitly:

val ages = mapOf(
    "Alice" to 25,
    "Bob" to 30
)

println(ages.isEmpty())              // false
println(ages.containsKey("Alice"))   // true
println(ages.containsValue(30))      // true
println("Bob" in ages)               // true, checks keys

You can also use contains():

val items = listOf("Book", "Pen")

println(items.contains("Book")) // true

In short:

  • collection.isEmpty() checks if it has no elements
  • collection.isNotEmpty() checks if it has at least one element
  • element in collection checks if an element exists
  • element !in collection checks if an element does not exist
  • map.containsKey(key) checks for a key
  • map.containsValue(value) checks for a value

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.