Kotlin Set any()
Syntax & Examples


Set.any() extension function

The any() extension function for sets in Kotlin returns true if the set has at least one element, or if at least one element matches the given predicate.


Syntax of Set.any()

There are 2 variations for the syntax of Set.any() extension function. They are:

1.
fun <T> Set<T>.any(): Boolean

This extension function returns true if the set has at least one element.

Returns value of type Boolean.

2.
fun <T> Set<T>.any(predicate: (T) -> Boolean): Boolean

This extension function returns true if at least one element matches the given predicate.

Returns value of type Boolean.



✐ Examples

1 Using any() to check if a set has any elements

In Kotlin, we can use the any() function to check if a set has any elements.

For example,

  1. Create a set of integers.
  2. Use the any() function to check if the set has any elements.
  3. Print the result to the console using the println function.

Kotlin Program

fun main(args: Array<String>) {
    val numbers = setOf(1, 2, 3)
    val hasElements = numbers.any()
    println("Does the set have any elements? $hasElements")
}

Output

Does the set have any elements? true

2 Using any() to check if any element is greater than 5

In Kotlin, we can use the any() function with a predicate to check if any element in a set of integers is greater than 5.

For example,

  1. Create a set of integers.
  2. Use the any() function with a predicate that checks if any element is greater than 5.
  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 anyGreaterThanFive = numbers.any { it > 5 }
    println("Is any number greater than 5? $anyGreaterThanFive")
}

Output

Is any number greater than 5? false

3 Using any() with an empty set

In Kotlin, we can use the any() function on an empty set, which will return false as there are no elements.

For example,

  1. Create an empty set of strings.
  2. Use the any() function to check if the set has any elements.
  3. Print the result to the console using the println function.

Kotlin Program

fun main(args: Array<String>) {
    val emptySet = emptySet<String>()
    val hasElements = emptySet.any()
    println("Does the empty set have any elements? $hasElements")
}

Output

Does the empty set have any elements? false

Summary

In this Kotlin tutorial, we learned about any() extension function of Set: the syntax and few working examples with output and detailed explanation for each example.