我是scala的新手,这里我有一个数组变量调用colarr
colarr: Array[(String, String)] = Array((empid,IntegerType), (empname,StringType), (address,StringType), (salary,IntegerType), (doj,TimestampType))
如何从中获取像empid和IntergerType这样的单个值?
答案 0 :(得分:3)
如果您想查看每个元组,可以使用Array.foreach
:
scala> val arr = Array(("hello", "world"), ("this", "isnice"), ("yay", "it works"))
scala> arr.foreach {
case (first, second) => println(s"First element $first, Second element: $second") }
First element hello, Second element: world
First element this, Second element: isnice
First element yay, Second element: it works
如果要从每个元组投影一个值,可以使用Array.map
:
scala> arr.map { case (first, second) => s"$first, $second" }
res1: Array[String] = Array(hello, world, this, isnice, yay, it works)
case (first, second)
只是创建部分函数的语法,它允许您从元组中提取第一个和第二个元素。
如果你想为初学者提供更简单的东西,你可以使用全部功能并使用元组的_.1
和_.2
元素:
scala> arr.map(tuple => s"${tuple._1}, ${tuple._2}")
res2: Array[String] = Array(hello, world, this, isnice, yay, it works)