Spark-shell&Scala(二)

2017-05-13  本文已影响82人  sf705

scala 循环

Scala循环中都没有 break和continue,所以用if条件了(for)

for循环

scala循环有点怪异,例如:for循环

for(变量名 <- a to b)     
eg: for(i <-1 to 10) print(i+" ") 输出:1 2 3 4 5 6 7 8 9 10

加条件的for循环

for(i<-1 to 10 if i%2 ==0)
     | print(i+",")
2,4,6,8,10,
scala> for(i<-1 to 10 if i%2==0; j<-1 to 2 if i%3 ==0)
     | print(i+",")
6,6,
scala> for(i<-1 to 10 if i%2==0; if i%3 ==0;j<-1 to 2 )
     | print(i+",")
6,6,
scala> for(i<-1 to 10 if i%2==0 if i%3 ==0;j<-1 to 2 )
     | print(i+",")
6,6,

while循环

scala> while(i<10)
     | {print(i+",")
     | i+=1
     | }
1,2,3,4,5,6,7,8,9,

while (条件) 条件中不能加上if条件判断

数组

数组有可变数组与不可变数组,可变需要导入包,在spark-shell中没有安装Scala,所以此处只有用不可变数组了

scala> var arr = Array(1,2,3,4,5)
arr: Array[Int] = Array(1, 2, 3, 4, 5)
scala> var arr2 = new Array[Int](5)
arr2: Array[Int] = Array(0, 0, 0, 0, 0)

scala> var arr = Array("hello"," world")
arr: Array[String] = Array(hello, " world")
scala> for(i<- 0 to 1)
     | print(arr(i)+",")
hello, world,

Map映射

map映射就是键值对的映射,和C++,Java中的Map差不多,都是不能重复
例如:

scala> val test1 = Map("a" -> 1,"b" -> 2,"a" -> 3)
test1: scala.collection.immutable.Map[String,Int] = Map(a -> 3, b -> 2)

scala> test1("b")
res4: Int = 2

scala> test1("a")
res3: Int = 3

Map 中的操作

scala> val test2 = Map("a" -> 1,"b" -> 2,"c" -> 3)
test2: scala.collection.immutable.Map[String,Int] = Map(a -> 1, b -> 2, c -> 3)

scala> test2.contains("a")
res6: Boolean = true

scala> test2.drop(1)
res14: scala.collection.immutable.Map[String,Int] = Map(b -> 2, c -> 3)

scala> test2.drop(2)
res15: scala.collection.immutable.Map[String,Int] = Map(c -> 3)

scala> test2.drop(3)
res16: scala.collection.immutable.Map[String,Int] = Map()

Tuple元组

scala> val tuple1 = (1 ,3,"hello",5,"world",3,1)
tuple1: (Int, Int, String, Int, String, Int, Int) = (1,3,hello,5,world,3,1)

scala> print(tuple1._1)
1
scala> print(tuple1._3)
hello

Set集合

scala中的Set集合和C++、Java中的都差不多,都是包含没有重复的元素

scala> val set1 = Set(1,7,5,3,8,3)
set1: scala.collection.immutable.Set[Int] = Set(5, 1, 7, 3, 8)
scala> var set3 = Set("a","b","c","a")
set3: scala.collection.immutable.Set[String] = Set(a, b, c)
// Int String 
scala> var set2= Set(1,2,3,"a","b")
set2: scala.collection.immutable.Set[Any] = Set(1, a, 2, b, 3)
上一篇下一篇

猜你喜欢

热点阅读