Kotlin List shuffled()
Syntax & Examples
Syntax of List.shuffled()
The syntax of List.shuffled() extension function is:
fun <T> Iterable<T>.shuffled(random: Random): List<T>
This shuffled() extension function of List returns a new list with the elements of this list randomly shuffled using the specified random instance as the source of randomness.
✐ Examples
1 Example
In this example,
- We create a list named
list
containing the integers[1, 2, 3, 4, 5]
. - We initialize a
Random
instance namedrandom
. - We shuffle the elements of
list
using theshuffled
function with the specifiedrandom
instance. - The result, which is a new list with the elements randomly shuffled, is stored in
shuffledList
. - Finally, we print the shuffled list to standard output using the
println
function.
Kotlin Program
import java.util.Random
fun main(args: Array<String>) {
val list = listOf(1, 2, 3, 4, 5);
val random = Random();
val shuffledList = list.shuffled(random);
println(shuffledList);
}
Output
[3, 2, 1, 4, 5]
2 Example
In this example,
- We create a list named
list
containing the characters['a', 'b', 'c', 'd', 'e']
. - We initialize a
Random
instance namedrandom
. - We shuffle the elements of
list
using theshuffled
function with the specifiedrandom
instance. - The result, which is a new list with the elements randomly shuffled, is stored in
shuffledList
. - Finally, we print the shuffled list to standard output using the
println
function.
Kotlin Program
import java.util.Random
fun main(args: Array<String>) {
val list = listOf('a', 'b', 'c', 'd', 'e');
val random = Random();
val shuffledList = list.shuffled(random);
println(shuffledList);
}
Output
[b, c, a, d, e]
3 Example
In this example,
- We create a list named
list
containing the strings['apple', 'banana', 'cherry', 'date', 'elderberry']
. - We initialize a
Random
instance namedrandom
. - We shuffle the elements of
list
using theshuffled
function with the specifiedrandom
instance. - The result, which is a new list with the elements randomly shuffled, is stored in
shuffledList
. - Finally, we print the shuffled list to standard output using the
println
function.
Kotlin Program
import java.util.Random
fun main(args: Array<String>) {
val list = listOf("apple", "banana", "cherry", "date", "elderberry");
val random = Random();
val shuffledList = list.shuffled(random);
println(shuffledList);
}
Output
[elderberry, date, cherry, banana, apple]
Summary
In this Kotlin tutorial, we learned about shuffled() extension function of List: the syntax and few working examples with output and detailed explanation for each example.