Sling Academy
Home/Kotlin/Using `first`, `last`, and `single` in Kotlin

Using `first`, `last`, and `single` in Kotlin

Last updated: November 30, 2024

Kotlin provides several functions to retrieve elements from collections efficiently. Three commonly used functions are first, last, and single. These functions offer simple and expressive ways to access specific elements under different conditions.

1. Using first in Kotlin

The first function returns the first element of a collection. If the collection is empty, it throws a NoSuchElementException. You can also specify a condition using a lambda expression to find the first element that matches a given predicate.

Examples:

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

    // Get the first element
    val firstNum = numbers.first()
    println("First number is: $firstNum") // Output: First number is: 1

    // Get the first even number
    val firstEven = numbers.first { it % 2 == 0 }
    println("First even number is: $firstEven") // Output: First even number is: 2
}

2. Using last in Kotlin

The last function works similarly to first, but it returns the last element of a collection. If no element satisfies the given condition or the collection is empty, it throws a NoSuchElementException.

Examples:

fun main() {
    val fruits = listOf("Apple", "Banana", "Cherry", "Date")

    // Get the last element
    val lastFruit = fruits.last()
    println("Last fruit is: $lastFruit") // Output: Last fruit is: Date

    // Get the last fruit that starts with 'C'
    val lastFruitWithC = fruits.last { it.startsWith('C') }
    println("Last fruit starting with C is: $lastFruitWithC") // Output: Last fruit starting with C is: Cherry
}

3. Using single in Kotlin

The single function returns the only element that matches a given condition. If there is no element or if more than one element satisfies the condition, it throws an IllegalArgumentException.

Examples:

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

    // Get the single element that is greater than 4 but less than 6
    val singleNum = numbers.single { it > 4 && it < 6 }
    println("Single number is: $singleNum") // Output: Single number is: 5

    // This would throw an exception because more than one element matches the condition
    // val invalidSingle = numbers.single { it % 2 != 0 }
}

Conclusion

The functions first, last, and single provide convenient ways to retrieve elements from collections in Kotlin with respect to specified conditions. While using them, it's crucial to handle potential exceptions appropriately to maintain robust code.

Next Article: Performing Aggregations in Kotlin: Sum, Count, and Average

Previous Article: Kotlin: Advanced Filtering with `filterIsInstance`

Series: Kotlin Collections

Kotlin

You May Also Like

  • How to Use Modulo for Cyclic Arithmetic in Kotlin
  • Kotlin: Infinite Loop Detected in Code
  • Fixing Kotlin Error: Index Out of Bounds in List Access
  • Setting Up JDBC in a Kotlin Application
  • Creating a File Explorer App with Kotlin
  • How to Work with APIs in Kotlin
  • What is the `when` Expression in Kotlin?
  • Writing a Script to Rename Multiple Files Programmatically in Kotlin
  • Using Safe Calls (`?.`) to Avoid NullPointerExceptions in Kotlin
  • Chaining Safe Calls for Complex Operations in Kotlin
  • Using the Elvis Operator for Default Values in Kotlin
  • Combining Safe Calls and the Elvis Operator in Kotlin
  • When to Avoid the Null Assertion Operator (`!!`) in Kotlin
  • How to Check for Null Values with `if` Statements in Kotlin
  • Using `let` with Nullable Variables for Scoped Operations in Kotlin
  • Kotlin: How to Handle Nulls in Function Parameters
  • Returning Nullable Values from Functions in Kotlin
  • Safely Accessing Properties of Nullable Objects in Kotlin
  • How to Use `is` for Nullable Type Checking in Kotlin