一、List
同Array一样,用来装同种类型元素的框,有序可重复。
定长List
Nil就是一个空的定长List
scala> Nil
res40: scala.collection.immutable.Nil.type = List()
集合的头
scala> l.head
res41: Int = 1
集合的尾巴
scala> l.tail
res42: List[Int] = List(2, 3, 4)
利用Nil拼接一个List
scala> val l2 = 1::2::3::Nil
l2: List[Int] = List(1, 2, 3)
变长List
scala> import scala.collection.mutable.ListBuffer
import scala.collection.mutable.ListBuffer
scala> val l = ListBuffer[Int]()
l: scala.collection.mutable.ListBuffer[Int] = ListBuffer()
----------------------------------------------
添加元素
scala> l+=1
res43: l.type = ListBuffer(1)
scala> l+=(2,3,4)
res44: l.type = ListBuffer(1, 2, 3, 4)
scala> l++=List(5,6,7)
res46: l.type = ListBuffer(1, 2, 3, 4, 5, 6, 7)
scala> l.append(8)
scala> l
res48: scala.collection.mutable.ListBuffer[Int] = ListBuffer(1, 2, 3, 4, 5, 6, 7, 8)
----------------------------------------------
删除元素
scala> l-=1
res49: l.type = ListBuffer(2, 3, 4, 5, 6, 7, 8)
移除下标为0的元素
scala> l.remove(0)
res51: Int = 2
scala> l
res52: scala.collection.mutable.ListBuffer[Int] = ListBuffer(3, 4, 5, 6, 7, 8)
二、Map
映射 key=value
定长Map
scala> val map = Map("zhangsan" -> 19 , "lisi" -> "20")
map: scala.collection.immutable.Map[String,Any] = Map(zhangsan -> 19, lisi -> 20)
scala> map("zhangsan")
res53: Any = 19
变长Map
scala> val a = scala.collection.mutable.Map("zhangsan" -> 19 , "lisi" -> "20")
a: scala.collection.mutable.Map[String,Any] = Map(lisi -> 20, zhangsan -> 19)
scala> a("lisi")
res54: Any = 20
HasMap
scala> val b = scala.collection.mutable.HashMap[String,Int]()
b: scala.collection.mutable.HashMap[String,Int] = Map()
scala> b("wangswu") = 30
scala> b+=("zhangsan" -> 19 , "lisi" -> 20)
res57: b.type = Map(lisi -> 20, zhangsan -> 19, wangswu -> 30)
scala> b-="wangswu"
res59: b.type = Map(lisi -> 20, zhangsan -> 19)
Map的迭代输出
package com.soul.bigdata.scala.day04
import scala.collection.mutable
object MapApp {
def main(args: Array[String]): Unit = {
// val m = mutable.HashMap()
val m = mutable.Map("zhangsan" -> 20, "lisi" -> 30)
//方法1
// for ((key,value) <- m){
// println(key + s":" + value)
// }
//方法2
// for (key <- m.keySet) {
// println(key + ":" + m.getOrElse(key, 0))
// }
//方法3
for (value <- m.values) {
println(value)
}
}
}
网友评论