Kotlin Set all()
Syntax & Examples


Set.all() extension function

The all() extension function for sets in Kotlin returns true if all elements in the set match the given predicate.


Syntax of Set.all()

The syntax of Set.all() extension function is:

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

This all() extension function of Set returns true if all elements match the given predicate.

Parameters

ParameterOptional/RequiredDescription
predicaterequiredA function that takes an element of the set and returns a Boolean indicating if the element matches the condition.

Return Type

Set.all() returns value of type Boolean.



✐ Examples

1 Using all() to check if all elements are even

In Kotlin, we can use the all() function to check if all elements in a set of integers are even.

For example,

  1. Create a set of integers.
  2. Use the all() function with a predicate that checks if each element is even.
  3. Print the result to the console using the println function.

Kotlin Program

fun main(args: Array<String>) {
    val numbers = setOf(2, 4, 6, 8, 10)
    val allEven = numbers.all { it % 2 == 0 }
    println("Are all numbers even? $allEven")
}

Output

Are all numbers even? true

2 Using all() to check if all strings have length greater than 3

In Kotlin, we can use the all() function to check if all elements in a set of strings have a length greater than 3.

For example,

  1. Create a set of strings.
  2. Use the all() function with a predicate that checks if each string has a length greater than 3.
  3. Print the result to the console using the println function.

Kotlin Program

fun main(args: Array<String>) {
    val fruits = setOf("apple", "banana", "cherry")
    val allLong = fruits.all { it.length > 3 }
    println("Do all fruits have length greater than 3? $allLong")
}

Output

Do all fruits have length greater than 3? true

3 Using all() with an empty set

In Kotlin, we can use the all() function on an empty set, which will return true as there are no elements to fail the predicate.

For example,

  1. Create an empty set of integers.
  2. Use the all() function with a predicate that checks if each element is positive.
  3. Print the result to the console using the println function.

Kotlin Program

fun main(args: Array<String>) {
    val emptySet = emptySet<Int>()
    val allPositive = emptySet.all { it > 0 }
    println("Are all numbers positive in the empty set? $allPositive")
}

Output

Are all numbers positive in the empty set? true

Summary

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