## 1. Overview

In this tutorial, we’ll see how we can shuffle some Scala collections like Lists, Maps, and Sets.

## 2. Shuffle a List

If we want to shuffle a List, or even other Scala collections like Seq and Array, we may start looking into coding our own implementation of some shuffling algorithm like the well-known Fisher-Yates shuffle. Unfortunately, it’s not as trivial as we may think at first. Bugs are easy to introduce and hard to detect.

Fortunately, the Scala standard lib already offers a way to achieve this, using the Random.shuffle() method:

``````scala> import scala.util.Random

scala> val lst = List(1,2,3,4,5)
val lst: List[Int] = List(1, 2, 3, 4, 5)

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

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

scala> Random.shuffle(lst)
val res2: List[Int] = List(3, 1, 4, 2, 5)``````

It’s worth noting that the Random.shuffle() method doesn’t modify the original collection – it returns a new shuffled collection.

## 3. Shuffle a Seq

The Random.shuffle() method also works with other collections like Seq:

``````scala> val seq = Seq(1,2,3,4,5)
val seq: Seq[Int] = List(1, 2, 3, 4, 5)

scala> Random.shuffle(seq)
val res3: Seq[Int] = List(4, 5, 1, 2, 3)

scala> Random.shuffle(seq)
val res4: Seq[Int] = List(1, 4, 2, 3, 5)

scala> Random.shuffle(seq)
val res5: Seq[Int] = List(3, 1, 5, 2, 4)``````

## 4. Shuffle a Map

We can use the same technique when working with Maps:

``````scala> val m = Map('a' -> 1, 'b' -> 2, 'c' -> 3)
val m: Map[Char, Int] = Map(a -> 1, b -> 2, c -> 3)

scala> Random.shuffle(m)
val res9: Map[Char, Int] = Map(c -> 3, a -> 1, b -> 2)

scala> Random.shuffle(m)
val res10: Map[Char, Int] = Map(a -> 1, b -> 2, c -> 3)

scala> Random.shuffle(m)
val res11: Map[Char, Int] = Map(c -> 3, a -> 1, b -> 2)``````

## 5. Shuffle a Set

However, if we try to shuffle a Set using Random.shuffle(), nothing happens:

``````scala> val set = Set(1,2,3,4,5)
val set: Set[Int] = HashSet(5, 1, 2, 3, 4)

scala> Random.shuffle(set)
val res6: Set[Int] = HashSet(5, 1, 2, 3, 4)

scala> Random.shuffle(set)
val res7: Set[Int] = HashSet(5, 1, 2, 3, 4)
``````

This is because a Set is already an unsorted collection. So it has no ordering guarantees.

## 6. Conclusion

In this article, we saw a very easy way to shuffle List, Seq, and Map in Scala. The approach uses the Random class from the standard lib.

Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.