shuffled()
FunctionCollections.shuffle()
The main idea behind randomizing a list is to change the order of its elements in a random fashion. In Kotlin, we can achieve this by leveraging built - in functions and methods. The key concepts involve using functions that generate a random permutation of the original list.
shuffled()
FunctionThe shuffled()
function is a Kotlin standard library function available for all collections. It returns a new list with the same elements as the original list but in a random order. The original list remains unchanged, which means this is a non - destructive operation.
Collections.shuffle()
This is a Java Collections framework method that can also be used in Kotlin. It shuffles the elements of a mutable list in place, meaning it modifies the original list directly.
shuffled()
Functionfun main() {
// Create a sample list
val originalList = listOf(1, 2, 3, 4, 5)
// Randomize the list using shuffled()
val randomizedList = originalList.shuffled()
println("Original List: $originalList")
println("Randomized List: $randomizedList")
}
In this code:
originalList
with five integer elements.shuffled()
function on originalList
to get a new list randomizedList
with the elements in a random order.Collections.shuffle()
import java.util.Collections
fun main() {
// Create a mutable list
val mutableList = mutableListOf(1, 2, 3, 4, 5)
// Shuffle the list in place
Collections.shuffle(mutableList)
println("Shuffled List: $mutableList")
}
In this example:
mutableList
with five integer elements.Collections
class from the Java standard library and call the shuffle()
method on mutableList
. This method shuffles the elements of the list in place.shuffled()
function to keep your code more functional and avoid side - effects. This is particularly useful in multi - threaded environments where modifying a shared mutable list can lead to race conditions.Random
object with a fixed seed. For example:import kotlin.random.Random
fun main() {
val originalList = listOf(1, 2, 3, 4, 5)
val random = Random(123) // Fixed seed
val randomizedList = originalList.shuffled(random)
println("Randomized List with fixed seed: $randomizedList")
}
shuffled()
function and Collections.shuffle()
are generally safe to use, you should still be aware of potential memory issues when working with extremely large lists.Randomizing a list in Kotlin is a simple yet powerful operation that can be used in a variety of scenarios. Whether you prefer the non - destructive shuffled()
function or the in - place Collections.shuffle()
method, Kotlin provides flexible ways to achieve randomization. By following the best practices, you can write more robust and reliable code.