LoginSignup
5
6

More than 5 years have passed since last update.

Multiple collection zipped in Scala

Last updated at Posted at 2015-03-11

Scalaでは2つのコレクションをまとめてループに回したい場合にzipを使うと便利なことがある。


scala> val l1 = Seq(1, 3, 5)
l1: Seq[Int] = List(1, 3, 5)

scala> val l2 = Seq(2, 4, 6)
l2: Seq[Int] = List(2, 4, 6)

scala> for ((a, b) <- (l1 zip l2)) yield (a, b)
res0: Seq[(Int, Int)] = List((1,2), (3,4), (5,6))

でもzipだと2つのコレクションをまとめることしたできないので3つ以上をまとめたい場合はzippedを使う。


scala> val l3 = Seq("a", "b", "c")
l3: Seq[String] = List(a, b, c)

scala> for ((a, b, c) <- (l1, l2, l3).zipped) yield (a, b, c)
res1: Traversable[(Int, Int, String)] = List((1,2,a), (3,4,b), (5,6,c))

参照
Can I zip more than two lists together in Scala?

5
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
6