简体   繁体   English

如何从Scala中的数据数组获取地图

[英]how to get map from array of data in scala

i am a newbie in scala, here i have an array variable call colarr 我是scala的新手,在这里我有一个名为colarr的数组变量

colarr: Array[(String, String)] = Array((empid,IntegerType), (empname,StringType), (address,StringType), (salary,IntegerType), (doj,TimestampType))

how to get individual value like empid and IntergerType from it? 如何从中获取单个值,如empid和IntergerType?

If you want to go over each tuple, you can use Array.foreach : 如果要遍历每个元组,可以使用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

If you want to project a value from each tuple, you can use Array.map : 如果要从每个元组中投影一个值,则可以使用Array.map

scala> arr.map { case (first, second) => s"$first, $second" }
res1: Array[String] = Array(hello, world, this, isnice, yay, it works)

The case (first, second) is just syntax for creating a partial function which allows you to extract the first and second element from the tuple. case (first, second)只是用于创建部分函数的语法,该函数允许您从元组中提取第一和第二个元素。

If you want something simpler for starters, you can a total function and work with _.1 and _.2 elements of the tuple: 如果您希望_.1者更简单一些,则可以使用全部功能并使用元组的_.1_.2元素:

scala> arr.map(tuple => s"${tuple._1}, ${tuple._2}")
res2: Array[String] = Array(hello, world, this, isnice, yay, it works)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM