1. Overview

In this tutorial, we’ll learn how to check if a certain condition is true for all elements in a Kotlin list. It can be achieved through various approaches. We’ll discuss the all() and none() functions, as well as filtering a list.

2. Check List With all() and none() Functions

The Kotlin standard library provides two convenient inline functions. The all() and none() functions allow us to check if a specific condition is true for all elements in a list. The all() function returns true if the given condition is valid for all elements in the list. Otherwise, it returns false.

Here’s an example:

@Test
fun `when all numbers greater than 0 then it returns true`() {
    val numbers = listOf(1, 2, 3, 4, 5, 6)
    val allGreaterThanZero = numbers.all { it > 0 }
    assertThat(allGreaterThanZero).isTrue
}

In the above code, we have a list of numbers. We want to check if all the numbers are greater than zero. The function is used with a lambda expression that checks if each element is greater than zero. Since all the elements in the list satisfy this condition, it returns true.

Similarly, the none() function returns true if the given condition is false for all elements in the list. Let’s consider the following example:

@Test
fun `when all numbers not greater than 10 then it returns true`() {
    val numbers = listOf(1, 2, 3, 4, 5, 6)
    val allLowerThanTen = numbers.none { it > 10 }
    assertThat(allLowerThanTen).isTrue
}

Again, we checked that all elements in the list pass the condition.

3. Check List Using Filters

Now, let’s check if a condition is true for all elements in a Kotlin list by using filters. We can filter the list based on the condition. Additionally, we can compare the filtered list’s size with the original list’s size.

Let’s look at an example:

@Test
fun `when all numbers greater than 5 then it returns true`() {
    val numbers = listOf(7, 8, 9, 10)
    val numbersGreaterThanFive = numbers.filter { it > 5 }
    assertThat(numbersGreaterThanFive).hasSize(numbers.size)
}

In the above code, we want to check if all the numbers are greater than 5. We apply a filter using the condition it > 5 to obtain a new list numbersGreaterThanFive. Finally, we compare the size of numbersGreaterThanFive with the size of the original list. If both sizes match, it means that all elements in the original list satisfy the condition.

4. Conclusion

In this article, we explored the all() and none() functions, which provide convenient ways to perform a check on all elements in a list.

Additionally, we saw how filters can be used to get the same result. Above all, the usage of all() and none() is more convenient. These methods return the information we need without additional checks.

As always, the source code of the examples is available over on GitHub.

Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.