🎓 A1Learner
🔍
0 of 48 lessons completed

Scala Grouping and Zip

Grouping is splitting a collection into smaller collections that share a key. Zip is pairing two collections item by item into one collection of pairs.

GroupBy splits numbers by remainder

Grouping by remainder puts the even numbers in one group and the odd numbers in another. The sorted keys show both groups exist.

@main def main(): Unit =
  val groups = List(1, 2, 3, 4).groupBy(_ % 2)
  println(groups.keys.toList.sorted)
  println(groups.getOrElse(0, List()))

Partition splits pass from fail

Partition keeps the passing scores in the first list and the rest in the second. Both lists keep their original order.

@main def main(): Unit =
  val (pass, fail) = List(40, 70, 55, 30).partition(_ >= 50)
  println(pass)
  println(fail)

Zip pairs names with scores

Zip pairs the first name with the first score, then the second name with the second score. The result is a list of pairs.

@main def main(): Unit =
  val pairs = List("ana", "bo").zip(List(90, 70))
  println(pairs)

Example

@main def main(): Unit =
  val names = List("ana", "bo", "cy")
  val scores = List(90, 40, 70)
  val pairs = names.zip(scores)
  val (pass, fail) = pairs.partition(_._2 >= 50)
  println(pass.map(_._1))
  println(fail.map(_._1))

Key points

  • GroupBy: groupBy splits a list into groups that share a key you pick.
  • Keys: the groups form a map, so read its sorted keys or one group, never the whole map.
  • Partition: partition splits a list into exactly two lists, the passing items and the rest.
  • Zip: zip pairs the first items together, then the second items, and so on.
  • ZipWithIndex: zipWithIndex pairs each item with its position, starting at zero.

In this example, zip first pairs each name with its score. Partition then splits those pairs into passing and failing groups, and each printed list shows only the names from its group.

Note

zip stops at the shorter list when the two lists have different lengths.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Scastie

Exercise

List(1, 2, 3).zip(List("a", "b")) pairs items one by one. What is the result?