Scala的Tuple拉链操作、Java Map与Scala Map的隐式转换
程序员文章站
2022-06-14 22:08:33
...
-
Tuple拉链操作指的就是zip操作
zip操作:指的就是数组的zip操作。zip方法是Array类的方法,就是将两个Array合并成一个Array,合并后也是一个Array,只不过里边的元素为Tuple。是Array类的方法,用于将两个Array,合并为一个Array
比如Array(v1)和Array(v2),使用zip操作合并后的格式为Array((v1,v2))
合并后的Array的元素类型为Tuple
val students = Array("Leo", "Jack", "Jen")
val scores = Array(80, 100, 90)
val studentScores = students.zip(scores)
for ((student, score) <- studentScores)
println(student + " " + score)
turple zip例子,eg.
package com.sunny.spark.scala.turple
/**
* <Description> <br>
*
* @author Sunny<br>
* @taskId: <br>
* @version 1.0<br>
* @createDate 2018/07/14 15:53 <br>
* @see com.sunny.spark.scala.turple <br>
*/
object TurpleZip {
def main(args: Array[String]): Unit = {
val v1 = Array("a", "b", "c")
val v2 = Array(1, 2, 3)
val v3 = v1.zip(v2)
/**
* 打印结果为
* (a,1)
* (b,2)
* (c,3)
*/
for (elem <- v3) {
println(elem)
}
val v3Map = v3.toMap
println(v3Map("a")) // 打印结果为 1
println(v3Map("b")) //打印结果为 2
println(v3Map("c")) //打印结果为 3
}
}
如果Array的元素类型是个Tuple,调用Array的toMap方法,可以将Array转换为Map
studentScores.toMap
-
Java Map与Scala Map隐式转换
Java Map转换Scala Map:在调用的函数前边导入隐式转换函数import scala.collection.JavaConversions.mapAsJavaMap
Scala Map转换Java Map:在调用的函数前边导入隐式转换函数import scala.collection.JavaConversions.mapAsScalaMap
eg.
import scala.collection.JavaConversions.mapAsScalaMap
val javaScores = new java.util.HashMap[String, Int]()
javaScores.put("Alice", 10)
javaScores.put("Bob", 3)
javaScores.put("Cindy", 8)
val scalaScores: scala.collection.mutable.Map[String, Int] = javaScores
import scala.collection.JavaConversions.mapAsJavaMap
import java.awt.font.TextAttribute._
val scalaAttrMap = Map(FAMILY -> "Serif", SIZE -> 12)
val font = new java.awt.Font(scalaAttrMap)