How do I access elements safely in Kotlin collections?

In Kotlin, you can access collection elements safely by using functions that return null instead of throwing exceptions when an index/key is missing.

Lists / arrays: use getOrNull

val items = listOf("A", "B", "C")

val first = items.getOrNull(0)   // "A"
val missing = items.getOrNull(10) // null

This is safer than:

val missing = items[10] // Throws IndexOutOfBoundsException

You can combine it with the Elvis operator:

val value = items.getOrNull(10) ?: "Default value"

Lists / arrays: use getOrElse

If you want a fallback value:

val items = listOf("A", "B", "C")

val value = items.getOrElse(10) { index ->
    "No item at index $index"
}

First / last elements safely

Instead of first() or last(), which throw if the collection is empty, use:

val items = emptyList<String>()

val first = items.firstOrNull()
val last = items.lastOrNull()

With a predicate:

val numbers = listOf(1, 2, 3, 4)

val firstEven = numbers.firstOrNull { it % 2 == 0 } // 2
val firstBig = numbers.firstOrNull { it > 10 }      // null

Single element safely

Use singleOrNull() when you expect exactly one matching element:

val users = listOf("Alice", "Bob")

val onlyAlice = users.singleOrNull { it == "Alice" } // "Alice"
val onlyZoe = users.singleOrNull { it == "Zoe" }     // null

Note: singleOrNull() also returns null if there is more than one match.

Maps: safe access by key

Map access already returns nullable values:

val ages = mapOf("Alice" to 30)

val aliceAge = ages["Alice"] // 30
val bobAge = ages["Bob"]     // null

Use a default if needed:

val bobAge = ages["Bob"] ?: 0

Or use getOrDefault:

val bobAge = ages.getOrDefault("Bob", 0)

Check bounds manually if needed

val items = listOf("A", "B", "C")
val index = 2

if (index in items.indices) {
    println(items[index])
}

Summary

Prefer these safe APIs:

list.getOrNull(index)
list.getOrElse(index) { default }
list.firstOrNull()
list.lastOrNull()
list.singleOrNull()
map[key] ?: default
map.getOrDefault(key, default)

Use direct indexing like list[index] only when you are certain the index is valid.

How do I loop through collections using for, foreach and indices in Kotlin?

In Kotlin, you can loop through collections in several common ways depending on whether you need the element, the index, or both.

1. Using for

Use for when you want a simple, readable loop over elements.

val names = listOf("Alice", "Bob", "Charlie")

for (name in names) {
    println(name)
}

Output:

Alice
Bob
Charlie

This works with many Kotlin types, including:

val numbers = arrayOf(1, 2, 3)

for (number in numbers) {
    println(number)
}

2. Using forEach

Use forEach when you prefer a functional style.

val names = listOf("Alice", "Bob", "Charlie")

names.forEach { name ->
    println(name)
}

If the lambda has only one parameter, you can use it:

names.forEach {
    println(it)
}

forEach is useful for concise operations, but a regular for loop is often clearer if you need break, continue, or more complex control flow.


3. Looping with indices

Use indices when you need the index of each element.

val names = listOf("Alice", "Bob", "Charlie")

for (i in names.indices) {
    println("Index $i: ${names[i]}")
}

Output:

Index 0: Alice
Index 1: Bob
Index 2: Charlie

indices gives the valid index range for the collection, such as 0..lastIndex.


4. Using withIndex

If you need both the index and the value, withIndex() is often cleaner than indexing manually.

val names = listOf("Alice", "Bob", "Charlie")

for ((index, name) in names.withIndex()) {
    println("Index $index: $name")
}

5. Using forEachIndexed

The forEach equivalent for index + value is forEachIndexed.

val names = listOf("Alice", "Bob", "Charlie")

names.forEachIndexed { index, name ->
    println("Index $index: $name")
}

Summary

val items = listOf("A", "B", "C")

// Element only
for (item in items) {
    println(item)
}

// Element only, functional style
items.forEach { item ->
    println(item)
}

// Index only / index-based access
for (i in items.indices) {
    println("items[$i] = ${items[i]}")
}

// Index and value
for ((index, item) in items.withIndex()) {
    println("$index -> $item")
}

// Index and value, functional style
items.forEachIndexed { index, item ->
    println("$index -> $item")
}

Use:

  • for (item in items) for simple iteration
  • items.forEach { ... } for concise functional-style iteration
  • items.indices when you need index-based access
  • withIndex() or forEachIndexed when you need both index and value

How do I reverse the order of array elements?

In this code snippet you’ll learn how to reverse the order of array elements. To reverse to element order will be using the Collections.reverse() method. This method requires an argument with List type. Because of this we need to convert the array to a List type first. We can use the Arrays.asList() to do the conversion. And then we reverse it. To convert the List back to array we can use the Collection.toArray() method.

Let’s see the code snippet below:

package org.kodejava.util;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class ArrayReverse {
    public static void main(String[] args) {
        // Creates an array of Integers and print it out.
        Integer[] numbers = {0, 1, 2, 3, 4, 5, 6, 7, 8};
        System.out.println("Arrays.toString(numbers) = " +
                Arrays.toString(numbers));

        // Convert the int arrays into a List.
        List<Integer> numberList = Arrays.asList(numbers);

        // Reverse the order of the List.
        Collections.reverse(numberList);

        // Convert the List back to array of Integers
        // and print it out.
        numberList.toArray(numbers);
        System.out.println("Arrays.toString(numbers) = " +
                Arrays.toString(numbers));
    }
}

The output of the code snippet above is:

Arrays.toString(numbers) = [0, 1, 2, 3, 4, 5, 6, 7, 8]
Arrays.toString(numbers) = [8, 7, 6, 5, 4, 3, 2, 1, 0]

How do I sort string of numbers in ascending order?

In the following example we are going to sort a string containing the following numbers "2, 5, 9, 1, 10, 7, 4, 8" in ascending order, so we will get the result of "1, 2, 4, 5, 7, 8, 9, 10".

package org.kodejava.util;

import java.util.Arrays;

public class SortStringNumber {
    public static void main(String[] args) {
        // We have some string numbers separated by comma. First we
        // need to split it, so we can get each individual number.
        String data = "2, 5, 9, 1, 10, 7, 4, 8";
        String[] numbers = data.split(",");

        // Convert the string numbers into Integer and placed it into
        // an array of Integer.
        Integer[] intValues = new Integer[numbers.length];
        for (int i = 0; i < numbers.length; i++) {
            intValues[i] = Integer.parseInt(numbers[i].trim());
        }

        // Sort the number in ascending order using the
        // Arrays.sort() method.
        Arrays.sort(intValues);

        // Convert back the sorted number into string using the
        // StringBuilder object. Prints the sorted string numbers.
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < intValues.length; i++) {
            Integer intValue = intValues[i];
            builder.append(intValue);
            if (i < intValues.length - 1) {
                builder.append(", ");
            }
        }
        System.out.println("Before = " + data);
        System.out.println("After  = " + builder);
    }
}

When we run the program we will get the following output:

Before = 2, 5, 9, 1, 10, 7, 4, 8
After  = 1, 2, 4, 5, 7, 8, 9, 10

How do I sort a java.util.Enumeration?

In this code snippet you will see how to sort the content of an Enumeration object. We start by creating a random numbers and stored it in a Vector. We use these numbers and create a Enumeration object by calling Vector‘s elements() method. We convert it to java.util.List and then sort the content of the List using Collections.sort() method. Here is the complete code snippet.

package org.kodejava.util;

import java.util.*;

public class EnumerationSort {
    public static void main(String[] args) {
        // Creates random data for sorting source. Will use java.util.Vector
        // to store the random integer generated.
        Random random = new Random();
        Vector<Integer> data = new Vector<>();
        for (int i = 0; i < 10; i++) {
            data.add(Math.abs(random.nextInt()));
        }

        // Get the enumeration from the vector object and convert it into
        // a java.util.List. Finally, we sort the list using
        // Collections.sort() method.
        Enumeration<Integer> enumeration = data.elements();
        List<Integer> list = Collections.list(enumeration);
        Collections.sort(list);

        // Prints out all generated number after sorted.
        for (Integer number : list) {
            System.out.println("Number = " + number);
        }
    }
}

An example result of the code above is:

Number = 20742427
Number = 163885840
Number = 204704456
Number = 560032429
Number = 601762809
Number = 1300593322
Number = 1371678147
Number = 1786580321
Number = 1786731301
Number = 1856215303