一、List
var x = List(1,2,3,4)
//x:List[Int] = List(1, 2, 3, 4)
var y = List("x","y","z")
//y: List[String] = List(x, y, z)
0 :: x
//res6: List[Int] = List(0, 1, 2, 3, 4)
x ::: y
//List[Any] = List(1, 2, 3, 4, x, y, z)
scala> "x"::"y"::"z"::Nil
res9: List[String] = List(x, y, z)
x.head //获取第一个元素
x.tail //获取除第一个元素的其他元素
x.isEmpty //判断该列表是否为空
字符串转List
var a = "HelloWorld,2018"
//a: String = HelloWorld,2018
a.toList
//res0: List[Char] = List(H, e, l, l, o, W, o, r, l, d, ,, 2, 0, 1, 8)
filter函数
a.toList.filter(x => Character.isDigit(x))
res1: List[Char] = List(2, 0, 1, 8)
//另一种简写方式
a.toList.filter(_.Character.isDigit(x))
takeWhile函数
a.toList.takeWhile(x => x!='d')
res2: List[Char] = List(H, e, l, l, o, W, o, r, l)
map函数
var a = List(1,2,3,4)
a.map(x => x % 2 == 0)
a.map(_%2 == 0)
var b = List(6,7,8)
var p = List(a,b)
a.map(_.filter(_%2 == 0))
//res14: List[List[Int]] = List(List(2, 4), List(8))
flatMap
a.flatMap(_.filter(_%2 == 0))
//res15: List[Int] = List(2, 4, 8)
reduce函数
a.reduce((x,y) => x+y)
//等价于
a.reduce(_+_)
foldLeft函数
a.fold(0)((x,y) => x+y)
//等价于
a.fold(0)(_+_)
二、Tuple元组
元组相当于数据库中的记录,可以放各种不同类型的值
val a = (1,2,3,4)
a._1 //访问元组中第一个元素
a._2 //访问元组中第二个元素
val b = (1,"fzj","math",95)
例子1:返回一条记录,计算一个列表的元素个数、元素之和,元素的平方和
val a = (1,2,3,4)
def sum(list:List[Int]):(Int,Int,Int)={
list.foldLeft(0,0,0)((x,y) => (x._1 + 1,x._2 + y,x._3 + y*y))
}
三、Set
var x = Set(1,2,3,4)
四、Map
(1) 创建Map
var x = Map("one" -> "1","two" -> "2")
var x:Map[String,String] = Map()
(2) 添加key-value
x += ("three" -> "three")
(3) 合并
使用 ++
运算符 或 Map.++()
方法来连接两个Map
var colors = color1 ++ color2
var colors = color1.++(color2)
(4) 遍历
val sites = Map("one"->"one","two"->"two","three"->"three")
sites.keys.foreach{
i =>
println("key="+i+",value="+sites(i))
}