How to shuffle (randomize) a list in Scala

As a quick note today, to shuffle/randomize a list in Scala, use this technique:

scala.util.Random.shuffle(List(1,2,3,4))

Here’s what this approach looks like in the Scala REPL:

import scala.util.Random

scala> val x = Random.shuffle(List(1,2,3,4))
x: List[Int] = List(2, 3, 1, 4)

scala> val x = Random.shuffle(List(1,2,3,4))
x: List[Int] = List(3, 4, 2, 1)

scala> val x = Random.shuffle(List(1,2,3,4))
x: List[Int] = List(1, 3, 4, 2)

You can also create a Random instance and call shuffle on it:

scala> val r = scala.util.Random
r: util.Random.type = scala.util.Random$@4715ae33

scala> val x = r.shuffle(List(1,2,3,4))
x: List[Int] = List(4, 2, 1, 3)

scala> val x = r.shuffle(List(1,2,3,4))
x: List[Int] = List(1, 4, 2, 3)

A key in this solution is to know that shuffle doesn’t randomize the List it’s given; instead it returns a new List that has been randomized (shuffled). This is consistent with functional programming principles, where you don’t modify the thing you are given, you return a modified version of it.

As a final note, you can use other Scala sequences with Random.shuffle like Seq and Vector.