CodeGym /Courses /Kotlin SELF /find/any/all/count: searching, checks, and counting witho...

find/any/all/count: searching, checks, and counting without manual loops

Kotlin SELF
Level 22, Lesson 2
Available

1. Introduction

When you’re just starting to program, the most natural reaction to a task like “find an element” or “count something” is to write a loop and do checks inside it. That’s normal: your brain honestly imitates how the processor works. But this approach has drawbacks: lots of boilerplate code, it’s easy to mess up break, it’s easy to forget the counter’s initial value, and sometimes the code ends up so scary that even you are afraid to touch it two days later.

The operations find, any, all, count are standard Kotlin functions for collections that express intent directly: “find”, “check that there is at least one”, “check that all”, “count”. They read almost like plain English, and the code becomes shorter. And it also helps separate “we compute” from “we print”, which makes the program more predictable.

There will be many examples below. We’ll start with very small lists, and then apply everything to our console mini app for expense tracking, which we’ve been building since the lessons about collections and commands.

2. find { ... }: find the first matching element and become friends with T?

find is a search operation. You give it a condition (a lambda predicate), and it returns the first element that matches. If no element matches, find returns null.

This is an important point: the result type will be nullable (T?), and the Kotlin compiler will require you to handle the “found nothing” case. This isn’t nitpicking; it’s protection: the program shouldn’t crash just because an element wasn’t found.

Let’s start with a simple example on numbers:

fun main() {
    val xs = listOf(1, 3, 4, 6)

    val firstEven: Int? = xs.find { it % 2 == 0 }
    println(firstEven) // 4
}

Here, firstEven is an Int?. Even if you can see with your eyes that an even number definitely exists, Kotlin still makes you live by the rules: “it might be null”. This discipline will later save you hours of debugging.

Now an example where the element doesn’t exist:

fun main() {
    val xs = listOf(1, 3, 5)

    val firstEven = xs.find { it % 2 == 0 }
    println(firstEven) // null
}

Notice: we didn’t do anything to “return null”. find is built that way: no matches — you get null. That’s the contract.

find in a CLI app: find an expense by id

We continue with a conditional CLI expense tracker. By convention (for now, without OOP) we’ll store one expense as Triple(id, category, amount), i.e. Triple<Int, String, Int>. It’s not an ideal model, but right now operations on collections matter more than a beautiful domain model.

Let’s implement expense lookup by id using find:

fun findExpenseById(
    expenses: List<Triple<Int, String, Int>>,
    id: Int
): Triple<Int, String, Int>? {
    return expenses.find { expense -> expense.first == id }
}

Now, in the place where we need to delete an expense, we don’t have to manually run through the list.

fun removeExpenseById(
    expenses: MutableList<Triple<Int, String, Int>>,
    id: Int
): Boolean {
    val found = expenses.find { it.first == id } ?: return false
    expenses.remove(found)
    return true
}

A neat thing happens here: if find returned null, the Elvis operator ?: immediately does return false. It reads almost like a conversation with the program: “if we didn’t find it, immediately report that deletion failed”.

3. any { ... } and all { ... }: “at least one” and “all match” checks

Sometimes we don’t need the element itself. We need a “yes/no” answer: are there elements that satisfy a condition? Or conversely: do all elements satisfy a condition? Before, you might create a flag like var ok = false and change it in a loop. Kotlin says, “don’t suffer” — there are any and all.

any { predicate } returns true if at least one element matches the condition. all { predicate } returns true if all elements match the condition. These are two operations that often live in validation and quick “can we continue?” checks.

Here’s an example:

fun main() {
    val words = listOf("a", "bb", "ccc")

    println(words.any { it.length == 2 }) // true
    println(words.all { it.isNotEmpty() }) // true
}

An important edge case: an empty collection

The most surprising part (and a classic beginner trap): the behavior of any and all on an empty collection.

fun main() {
    val empty = emptyList<Int>()

    println(empty.any { it > 0 }) // false
    println(empty.all { it > 0 }) // true
}

This is not a bug and not “Kotlin being weird”. This logic comes from mathematics:

— any on an empty set is false, because “there is not a single element that would confirm the condition”.
— all on an empty set is true, because “there is not a single counterexample”. Nobody violated the rule — formally, the rule holds.

To make this easier to remember, here’s a small table:

Collection Check Result Intuition
[]
any { ... }
false
“There’s nobody — so nobody matches”
[]
all { ... }
true
“There’s nobody — so nobody violated the condition”

When does this matter? For example, if you check “all amounts are positive”. If the list is empty, all will say true. Sometimes that’s what you want (an empty list contains no errors). And sometimes you want to separately check “the list is not empty”, but that’s already business logic, not a problem with all.

any/all in a CLI app: quick data checks

Suppose we want to know: are there any very large expenses (say, more than 10_000)? That’s a pure any:

fun hasBigExpenses(
    expenses: List<Triple<Int, String, Int>>
): Boolean {
    return expenses.any { it.third > 10_000 }
}

And conversely: we want to check that all amounts are valid (for example, strictly greater than zero). That’s all:

fun allExpensesPositive(
    expenses: List<Triple<Int, String, Int>>
): Boolean {
    return expenses.all { it.third > 0 }
}

It’s important to keep the meaning in your head: any/all is not “like an if”, it’s “an answer to a question”. And the more precise your question, the cleaner the code.

4. count { ... }: counting without an external counter

count is an operation that returns the number of elements in a collection. It has two modes.

If you call count() without a condition, you get the collection size (same as size, but sometimes it’s convenient specifically as an “operation” in a chain of reasoning). If you call count { predicate }, you get the number of elements satisfying the condition. Kotlin documentation classifies count as an aggregating operation: you return a single value based on the collection contents.

Mini example:

fun main() {
    val xs = listOf(1, 2, 3, 4, 5)

    val evenCount = xs.count { it % 2 == 0 }
    println(evenCount) // 2
}

Why count { ... } is better than filter { ... }.size

Yes, you can write:

val evenCount = xs.filter { it % 2 == 0 }.size

This will work. But semantically, you do “filtering” (you get a list) and then take its size. But you didn’t want a list — you wanted a number. count expresses intent more precisely and reads more easily: “count elements that match the condition”. Plus, you don’t create an intermediate list (that’s an efficiency question, but even without going deep it’s nice to know Kotlin isn’t doing extra work for you).

count in a CLI app: simple statistics

Let’s write a couple of functions that count how many expenses we have in a specific category, and how many total:

fun totalExpenseCount(expenses: List<Triple<Int, String, Int>>): Int {
    return expenses.count()
}

fun countByCategory(
    expenses: List<Triple<Int, String, Int>>,
    category: String
): Int {
    return expenses.count { it.second == category }
}

Note: count() returns an Int, and count { ... } also returns an Int. So it’s a “final result” that you can print, store, compare in an if, and so on.

5. Practical example: the remove and stats commands in a CLI

Now let’s write a piece of “practical” code for our console app: we’ll add a delete-by-id command using find, and a stats command that shows several answers using count/any/all. Important: we’re not building a perfect project; we’re practicing collection operations, so the code will be as straightforward as possible and in small chunks.

Printing one expense

Let’s create a utility to print an expense:

fun printExpense(expense: Triple<Int, String, Int>) {
    val id = expense.first
    val category = expense.second
    val amount = expense.third

    println("#$id | $category | $amount")
}

Command remove: “found → removed” without manual iteration

fun handleRemove(
    expenses: MutableList<Triple<Int, String, Int>>,
    id: Int
) {
    val found = expenses.find { it.first == id }

    if (found == null) {
        println("Expense with id=$id not found")
        return
    }

    expenses.remove(found)
    println("Removed:")
    printExpense(found)
}

There are several useful ideas here right away.

First, find returns Triple<...>?, and we honestly check for null. That’s exactly what Kotlin means by “writing code that survives in the real world”.

Second, we remove by the object found, not by index. For a MutableList this is a normal and clear approach: found an element — removed that element.

Command stats: count and check without loops

fun printStats(expenses: List<Triple<Int, String, Int>>) {
    val total = expenses.count()
    val foodCount = expenses.count { it.second == "food" }
    val hasNegative = expenses.any { it.third < 0 }
    val allPositive = expenses.all { it.third > 0 }

    println("Total expenses: $total")
    println("In category food: $foodCount")
    println("Has negative amounts: $hasNegative")
    println("All amounts are positive: $allPositive")
}

Notice how this code reads: it’s almost like the text of a report. And the best part is that you don’t need a var counter, you don’t need to remember break, and you don’t need to write four loops in a row.

A useful trick: find a problematic element with find

If allPositive suddenly becomes false, you usually want to know “what exactly is broken?”. It’s convenient to do a find with the same condition, just inverted:

fun printFirstNegative(expenses: List<Triple<Int, String, Int>>) {
    val bad = expenses.find { it.third < 0 }

    if (bad != null) {
        print("First suspicious expense: ")
        printExpense(bad)
    }
}

any answers the question “does a problem exist?”, and find helps show an “example of the problem”. This is a very practical combo: validation + diagnostics.

6. Typical mistakes when using find/any/all/count

Mistake #1: forgetting that find returns T?, and treating the result as non-null.
The most common story looks like this: you wrote val x = list.find { ... }, and then immediately println(x.first) (or x.length if it’s a string). The compiler won’t let you do that — and rightly so. You need to either check x != null, or use a safe-call x?.first, or define default behavior via Elvis ?:. Once you get used to it, the code becomes more robust and “random crashes” disappear as a genre.

Mistake #2: confusing find and filter, expecting “all matches” rather than “the first match”.
find returns one element (the first), not a list. If you need to collect all matching elements, that’s the filter style (we discussed it in the previous lecture about map/filter). The mistake usually shows up quietly: you think you found “all large expenses”, but in reality you found only the first one and calmed down. This is one of those bugs that especially likes to live in reports.

Mistake #3: being surprised by the behavior of all on an empty collection.
If your expenses is empty, expenses.all { it.third > 0 } will return true. This is correct by contract, but sometimes it doesn’t match the meaning “we have at least some data”. If it’s important for you to distinguish “everything is OK” from “we have no data”, add a separate emptiness check where the business rule is formulated. It’s important to understand: all is not “wrong”; it honestly answers the question you asked.

Mistake #4: using count where a check is needed, and forgetting about intent.
Sometimes people write something like if (xs.count { it < 0 } > 0) ... This works, but it reads a bit heavy: first we count, then we compare. If semantically you want “is there at least one negative”, then any { it < 0 } expresses it more simply. count is great when you truly need a number.

Mistake #5: trying to do side effects inside any/all and then being surprised by the logic.
Technically you can write xs.any { println(it); it < 0 }, but you’ll get a “strange” effect: any will stop at the first match and won’t print all elements. This isn’t a bug — it’s short-circuiting (operations can finish earlier than iterating the whole list). So printing and other “actions” are better kept separate, and any/all/find/count should be used as pure questions to the data.

Mistake #6: forgetting that count { ... } traverses the whole collection, while find/any/all can stop earlier.
In small educational examples you won’t see the difference, but on large lists it can be noticeable: find/any/all often finish on an early match or violation, while count must count to the end. Even if you’re not thinking about performance yet, it’s useful to understand “why an operation might be faster” — it helps you write more intentional code.

1
Task
Kotlin SELF, level 22, lesson 2
Locked
Luck Scanner
Luck Scanner
1
Task
Kotlin SELF, level 22, lesson 2
Locked
Password check
Password check
1
Task
Kotlin SELF, level 22, lesson 2
Locked
Range Sensor
Range Sensor
1
Task
Kotlin SELF, level 22, lesson 2
Locked
Count above the threshold
Count above the threshold
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION