Skip to content
Tutorials Center
My learning

Topics

Lesson 40 of 134 ยท Collections

Accessing and Searching

Learn how to read and search Kotlin collections: first, last, find, getOrNull, take, drop, slice, indexOf, any, all, none and the exceptions that first() and single() can throw.

Once you have a collection, you constantly ask small questions about it. What is the first element? Is there an element above 100? Where is "kiwi"? Give me the first three. Do all of these pass the check? Kotlin has a precise function for each question, and, more importantly, a pair of functions for each: one that throws when the answer does not exist and one that returns null.

Choosing between the two is the main skill of this lesson. You will see every access function, the exact exception each throwing version produces, the safe alternatives, and how to take slices of a collection without writing index arithmetic. If you need a refresher on the collection types themselves, read Lists and Collections Overview first.

Reading elements by position

Kotlin first, last, indexing and safe access

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The output is 10, 60, 30, 40, 50, 5, 0..5, null, -1, null, 10 and null.

  • first() and last() return the ends. xs[i] and xs.get(i) are the same thing; the bracket form is the usual one. elementAt(i) also works on collections that have no index, such as a Set or a sequence, by walking to the position.
  • lastIndex is size - 1, and indices is the range 0..lastIndex, handy in for (i in xs.indices).
  • getOrNull(i), elementAtOrNull(i), getOrElse(i) { default }, firstOrNull() and lastOrNull() never throw. They return null (or your fallback) when the position does not exist.

When access fails

The plain versions throw, and each throws a different exception with its own message. Seeing them once makes them easy to recognise in a real stack trace.

Kotlin Index out of range (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The program ends with Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 3. The exact class depends on the list implementation behind listOf (an ArrayList would throw IndexOutOfBoundsException, its parent class), so catch IndexOutOfBoundsException if you must catch anything. The better fix is to avoid the exception: check i in xs.indices or use getOrNull(i).

Kotlin first on an empty list (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

This one stops with java.util.NoSuchElementException: List is empty. The same happens for last(). Use firstOrNull() when the list may be empty.

Searching by condition: first, find, single

Often you do not know the position; you know a property. first { } and firstOrNull { } return the first element for which the lambda is true, and last / lastOrNull search from the end. find is just another name for firstOrNull { }, and findLast for lastOrNull { }.

Kotlin Finding by condition

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

You see 40, 40, 30, null, 30 and 30. Note that lastOrNull { it < 35 } is 30, not 10: it scans from the end and returns the first match it meets.

Two conditions deserve their own failure demonstrations, because both are common bugs:

Kotlin first with no match (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The result is java.util.NoSuchElementException: Collection contains no element matching the predicate. The message names the problem exactly: there was no match. Use firstOrNull { } and handle null.

Kotlin single with several matches (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

single { } demands exactly one match, and here there are two (3 and 4), so it throws java.lang.IllegalArgumentException: Collection contains more than one matching element. With zero matches it throws NoSuchElementException instead. singleOrNull { } returns null in both of those cases, which makes it ambiguous: you cannot tell "none" from "too many". Reach for single when uniqueness is an invariant you want enforced, such as looking up an item by a primary key.

A good habit: prefer the OrNull variant at the edge of your program, where data may be missing, and the throwing variant deep inside logic where a missing value means a bug. A crash with a clear message is a feature when it flags a broken assumption.

Slices: take, drop and friends

To get a part of a collection, you do not need loops or index math:

Kotlin take, drop, slice and subList

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The twelve lines are [1, 2, 3], [7, 8], [6, 7, 8], [1, 2], [1, 2, 3], [6, 7, 8], [7, 8], [2, 3, 4], [1, 8], [3, 4, 5], 8 and [].

  • take(n) and takeLast(n) keep the first or last n; drop(n) and dropLast(n) do the opposite. They are forgiving: asking for more than exists just returns everything (or nothing), as the last two lines show. No exception.
  • takeWhile and dropWhile use a condition instead of a count and stop at the first element that breaks it. takeWhile { it < 4 } stops at 4 even if later elements would pass.
  • slice takes a range or a list of indices, in any order. It copies the elements.
  • subList(from, to) is a view of the original (the to index is exclusive). It does not copy, but it is tied to the source list and becomes invalid if you add or remove elements of that list. It throws IndexOutOfBoundsException if the range is bad, unlike take and drop.

take(n) is also the safe way to preview data: println(bigList.take(5)).

Where is it? indexOf and contains

Kotlin indexOf, contains and binarySearch

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The output is 1, 3, -1, 1, 4, true, true, 2, 3 and -3.

  • indexOf(x) returns the first position, lastIndexOf(x) the last, and both return -1 when the element is absent. Forgetting to check for -1 is a classic bug: xs[xs.indexOf("z")] crashes because index -1 is invalid.
  • indexOfFirst { } and indexOfLast { } search by condition and also return -1 when nothing matches.
  • x in xs is the operator form of contains. On a List it scans every element, which is O(n). If you test membership often, build a Set first (O(1) on average).
  • binarySearch needs a sorted list and is O(log n). A found element returns its index; a missing one returns -(insertionPoint) - 1, so searching for 4 returns -3, meaning "it would go at index 2". On an unsorted list the answer is meaningless, and Kotlin does not warn you.

Asking yes/no questions: any, all, none

These three never return an element; they answer a question about the whole collection:

Function True when On an empty collection
any { } at least one element matches false
all { } every element matches true
none { } no element matches true

Without a lambda, any() means "is not empty" and none() means "is empty", though isNotEmpty() and isEmpty() read better. The surprising entry is all on an empty collection: with no elements nothing can break the rule, so the answer is true. If you need "at least one element and all of them match", combine them: isNotEmpty() && all { }.

The functions stop as soon as the answer is known (short-circuit): any stops at the first match, all at the first failure. That matters when the predicate is expensive.

A realistic example

Kotlin Looking up users

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The lines are bo, no user 9, cy, true, false, true, (2, 1), null, User(id=0, name=guest, admin=false) and BO. Two patterns are worth stealing:

  • Safe lookup with a default: firstOrNull { }?.property ?: fallback. The ?. and ?: operators from Null Safety turn a possible null into a clean result in one line.
  • Many lookups: build a map once. Calling find { it.id == x } for every request scans the list each time (O(n) per lookup). associateBy { it.id } pays O(n) once, then every lookup is O(1).

firstNotNullOfOrNull { } combines a search and a transformation: it returns the first non-null result of the lambda, here the upper-cased name of the first admin.

The same functions elsewhere

Most of these functions are defined on every kind of collection, and many on strings and arrays too, so what you learn here carries over:

Kotlin Strings, arrays, sequences and destructuring

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

You see k, n, kot, lin, null, 2, 1 2 3, 10, 8 and 8. A string is a sequence of characters, so first, take and drop work on it. Destructuring val (x, y, z) = a uses component1() to component5(), which lists provide for their first five elements; it throws IndexOutOfBoundsException if the list is too short, so use it only when the size is known. On a sequence, first { } processes elements lazily and stops at the first match.

Pitfalls

  • xs[i] with a bad index throws; guard it or use getOrNull.
  • first() on a possibly empty list throws NoSuchElementException; use firstOrNull().
  • single with duplicates throws IllegalArgumentException; use it only for true uniqueness.
  • Ignoring -1 from indexOf and then using it as an index.
  • subList views go stale when the source list changes; copy with toList() if you keep them.
  • binarySearch on unsorted data returns garbage without any error.
  • Repeated find/contains on a big list is O(n) each time; use a Map or Set.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does listOf(1, 2, 3).first { it > 5 } do?

    first { } throws NoSuchElementException when nothing matches. firstOrNull { } would return null.
  2. 2. Which call returns [3, 4, 5] for listOf(1, 2, 3, 4, 5, 6)?

    drop(2) removes 1 and 2, and take(3) keeps the next three: [3, 4, 5]. slice(3..5) would give [4, 5, 6].
  3. 3. What does emptyList<Int>().all { it > 0 } return?

    With no elements, no element can violate the condition, so all is vacuously true.
  4. 4. What does listOf(1, 2, 3, 4).single { it > 2 } do?

    single { } requires exactly one match. Two matches throw IllegalArgumentException, and no match throws NoSuchElementException.
  5. 5. What does listOf(1, 3, 5).binarySearch(4) return?

    A missing element gives -(insertionPoint) - 1; for 4 in [1, 3, 5] that is -3. The list must be sorted.

Summary

  • Position access: first(), last(), xs[i], elementAt(i) throw when the position is missing; firstOrNull(), lastOrNull(), getOrNull(i) and getOrElse(i) { } do not.
  • Search by condition: first { }, find { }, last { }, single { } and their OrNull forms; single demands exactly one match.
  • Slice with take, takeLast, drop, dropLast, takeWhile, dropWhile and slice; they are forgiving about sizes, while subList is a view that throws on bad ranges.
  • indexOf returns -1 when absent; binarySearch needs sorted data.
  • any, all and none answer yes/no questions and short-circuit; all and none are true for empty collections.
  • For many lookups, build a Map or Set once.

Next: Mutable Collections and Iterators