Sling Academy
Home/Kotlin/Reversing and Shuffling Lists in Kotlin

Reversing and Shuffling Lists in Kotlin

Last updated: December 05, 2024

Kotlin, a modern programming language, is highly regarded for its straightforward syntax and interoperability with Java. When it comes to collection manipulation, particularly lists, Kotlin offers extensive support to make programming enjoyable and efficient. In this article, we'll dive into reversing and shuffling lists using Kotlin, exploring the functions available and providing ample examples to illustrate these operations.

Reversing Lists

Reversing a list means changing its items order by flipping it end to end. Kotlin provides a couple of approaches to reverse a list: reversed() and reverse(). Understanding these methods will empower you to use the most appropriate one for any given scenario effectively.

Using reversed()

The reversed() function returns a new list with the elements reversed. The original list remains unchanged, making this method ideal when immutability is preferred. Here's an example:


fun main() {
    val originalList = listOf(1, 2, 3, 4, 5)
    val reversedList = originalList.reversed()
    println("Original List: $originalList")
    println("Reversed List: $reversedList")
}

The output will be:


Original List: [1, 2, 3, 4, 5]
Reversed List: [5, 4, 3, 2, 1]

Using reverse()

The reverse() function is applicable on mutable lists. It reverses the list in-place, altering the original collection directly. This can be useful for performance when working with large data where creating a copy is unnecessary.


fun main() {
    val mutableList = mutableListOf("A", "B", "C", "D")
    println("Original MutableList: $mutableList")
    mutableList.reverse()
    println("Reversed MutableList: $mutableList")
}

The output will be:


Original MutableList: [A, B, C, D]
Reversed MutableList: [D, C, B, A]

Shuffling Lists

Sometimes, you might want to randomize the order of elements in a list. Kotlin's standard library provides us with the shuffled() and shuffle() methods to handle these scenarios conveniently.

Using shuffled()

The shuffled() function creates a new list where the elements are randomly shuffled, leaving the original list untouched.


fun main() {
    val items = listOf(1, 2, 3, 4, 5)
    val shuffledItems = items.shuffled()
    println("Original List: $items")
    println("Shuffled List: $shuffledItems")
}

The output might look like:


Original List: [1, 2, 3, 4, 5]
Shuffled List: [3, 5, 2, 1, 4]

Using shuffle()

The shuffle() function is for mutable lists and modifies the list in-place to randomize its order. This is advantageous for immediate manipulations without requiring duplicate allocations.


fun main() {
    val mutableItems = mutableListOf("Apple", "Banana", "Cherry")
    println("Original MutableList: $mutableItems")
    mutableItems.shuffle()
    println("Shuffled MutableList: $mutableItems")
}

The output might vary, as it will provide a different order each time:


Original MutableList: [Apple, Banana, Cherry]
Shuffled MutableList: [Banana, Cherry, Apple]

Conclusion

Reversing and shuffling are common tasks that Kotlin makes simple with its built-in library functions. Whether working with immutable or mutable works of data, Kotlin provides the functionality to reverse and shuffle conveniently. Understanding the differences between in-place operations and those which return new instances is crucial for writing efficient Kotlin applications.

Next Article: Checking if a List Contains a Given Value in Kotlin

Previous Article: Grouping Lists by a Property in Kotlin

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