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
- 表示变量 i 从1 到10,即:[1,10]
- 其中
<-
该符号中间不能有空格,写成 :< -
就会出错
加条件的for循环
for(i<-1 to 10 if i%2 ==0)
| print(i+",")
2,4,6,8,10,
- 上面i 范围为:[1,10],不过加上了一个条件:判断i的奇偶性
- 如果出现两个及以上循环for,则加上分号
- for循环中两个及以上的 if 条件之间不用加分号,如下所示
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,
- 将数组arr 初始化为两个字符串
- 在调用数组各个变量时,用arr(i),而不是arr[i],i 从0 开始
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(key1 -> value1,key2 -> value2)
- 变量名(key) 输出对应的value
- 如果key 有重复的,过滤掉,取最后出现的一个value作为该key的value
Map 中的操作
- contains(key),如果有该key,返回true,否则 false
- getOrElse(key,num),如果有该key,返回对应的value,如果没有返回num
- drop(loc),返回从位置为loc之后的所有map对,从0开始,如下面所示
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元组
- 元组里面可以存放多种类型的数据
- 原则遍历是通过:元组名._loc,(元组名,点,下划线,元素位置)
- 元组中元素位置从1开始
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中的都差不多,都是包含没有重复的元素
- 可以存放多种类型,如String、Int混用
- 操作有:head,tail ,isEmpty,contains,drop 等
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)