美图欣赏:
一.背景
元组在操作Spark中还是非常多的
二.元组(Tuple)
映射是K/V对偶的集合,对偶是元组的最简单形式,元组可以装着多个不同类型的值,是不同类型的值的聚集。
三.代码举例
映射是K/V对偶的集合,对偶是元组的最简单形式,元组可以装着多个不同类型的值,是不同类型的值的聚集。
scala> val tuple = (1, "Jackson" , 2.5 , 100L , 20F)
tuple: (Int, String, Double, Long, Float) = (1,Jackson,2.5,100,20.0)
scala> tuple._1
res39: Int = 1
scala> tuple._2
res40: String = Jackson
scala> val tuple1 = new Tuple3(1,2,3)
tuple1: (Int, Int, Int) = (1,2,3)
scala> val tuple1 = new Tuple2(4,5)
tuple1: (Int, Int) = (4,5)
scala> val tuple1 = new Tuple1(1,2,3)
tuple1: ((Int, Int, Int),) = ((1,2,3),)
目前 Scala 支持的元组最大长度为 22。对于更大长度你可以使用集合,或者扩展元组。
//源码
@deprecatedInheritance("Tuples will be made final in a future version.", "2.11.0")
case class Tuple22[+T1, +T2, +T3, +T4, +T5, +T6, +T7, +T8, +T9, +T10, +T11, +T12, +T13, +T14, +T15, +T16, +T17, +T18, +T19, +T20, +T21, +T22](_1: T1, _2: T2, _3: T3, _4: T4, _5: T5, _6: T6, _7: T7, _8: T8, _9: T9, _10: T10, _11: T11, _12: T12, _13: T13, _14: T14, _15: T15, _16: T16, _17: T17, _18: T18, _19: T19, _20: T20, _21: T21, _22: T22)
extends Product22[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22]
{
override def toString() = "(" + _1 + "," + _2 + "," + _3 + "," + _4 + "," + _5 + "," + _6 + "," + _7 + "," + _8 + "," + _9 + "," + _10 + "," + _11 +
"," + _12 + "," + _13 + "," + _14 + "," + _15 + "," + _16 + "," + _17 + "," + _18 + "," + _19 + "," + _20 + "," + _21 + "," + _22 + ")"
}
scala> val tup,(x,y,z)=(1,2,3)
tup: (Int, Int, Int) = (1,2,3)
x: Int = 1
y: Int = 2
z: Int = 3
scala> x
res41: Int = 1
scala> y
res42: Int = 2
scala> z
res43: Int = 3
scala> tup.toString
res44: String = (1,2,3)
scala> val tup1 = (1,2)
tup1: (Int, Int) = (1,2)
//swap进行转换(只能俩元素)
scala> tup1.swap
res45: (Int, Int) = (2,1)
//元组遍历
//方式1:
for (elem <- tuple1.productIterator) {
print(elem)
}
println()
//方式2:
tuple1.productIterator.foreach(i => println(i))
tuple1.productIterator.foreach(print(_))
————保持饥饿,保持学习
Jackson_MVP
转载:https://blog.csdn.net/Jackson_mvp/article/details/104638998
查看评论