Scala List 用法

1.++[B]   在A元素后面追加B元素

scala> val a = List(1)
a: List[Int] = List(1)

scala> val b = List(2)
b: List[Int] = List(2)

scala> val c = a ++ b
c: List[Int] = List(1, 2)

scala> val d = List('a')
d: List[Char] = List(a)

scala> val e = c ++ d
e: List[AnyVal] = List(1, 2, a)

2.++: 与++不同的是使用的右边边的数据类型

scala> val x = List(1)
x: List[Int] = List(1)

scala> val y = LinkedList(2)
y: scala.collection.mutable.LinkedList[Int] = LinkedList(2)

scala> var z = x ++: y
z: scala.collection.mutable.LinkedList[Int] = LinkedList(1, 2) //y是LinkedList
scala> var z = y ++: x  //使用x的类型
z: List[Int] =List(1, 2)

3.+:  在List的头部增加元素

scala> val x = List(1)
x: List[Int] = List(1)

scala> val y = 2 +: x
y: List[Int] = List(2, 1)

scala> println(x)
List(1)

4./:应用二进制运算符起始值,从左到右遍历迭代所有元素。

scala> val a = List(1,2,3,4)
a: List[Int] = List(1, 2, 3, 4)

scala> val b = (5 /: a)(_+_)
b: Int = 15

scala> val c = (5 /: a)((x,y) => x + y)
c: Int = 15

5.:+:在后面追加元素

scala> val a = List(1)
a: List[Int] = List(1)

scala> val b = a :+ 2
b: List[Int] = List(1, 2)

scala> println(a)
List(1)

6.:: 为列表增加单个元素,这是一个右结合的操作符

1 :: List(2, 3) = List(2, 3).::(1) = List(1, 2, 3)

7.::: 在列表的前面追加一个列表,这是一个右结合的操作符

List(1, 2) ::: List(3, 4) = List(3, 4).:::(List(1, 2)) = List(1, 2, 3, 4)

8.:\ 与元素合并后按照操作进行对列表遍历

scala> val a = List(1,2,3,4)
a: List[Int] = List(1, 2, 3, 4)

scala> val b = (a :\ 5)(_+_)
b: Int = 15

scala> val c = (a :\ 5)((x,y) => x + y)
c: Int = 15

9.addString(b: StringBuilder) 对列表中的所有元素迭代将拼接成字符串

scala> val a = List(1,2,3,4)
a: List[Int] = List(1, 2, 3, 4)

scala> val b = new StringBuilder()
b: StringBuilder =

scala> val h = a.addString(b)
h: StringBuilder = 1234

10.addString(b: StringBuildersep: String) 使用分隔符输出字符串

scala> val a = List(1,2,3,4)
a: List[Int] = List(1, 2, 3, 4)

scala> val b = new StringBuilder()
b: StringBuilder =

scala> a.addString(b, ", ")
res0: StringBuilder = 1, 2, 3, 4

11.addString(b: StringBuilderstart: Stringsep: Stringend: String) 定义输出以什么开始、分割、结束

scala> val a = List(1,2,3,4)
a: List[Int] = List(1, 2, 3, 4)

scala> val b = new StringBuilder()
b: StringBuilder =

scala> a.addString(b , "List(" , ", " , ")")
res5: StringBuilder = List(1, 2, 3, 4)

12. aggregate[B](z: ⇒ B)(seqop: (B, A) ⇒ B, combop: (B, B) ⇒ B)B 对列表内元素进行求和

List('a', 'b', 'c').aggregate(0)({ (sum, ch) => sum + ch.toInt }, { (p1, p2) => p1 + p2 })

13.apply(n: Int) 通过索引选择元素

scala> List('a','b','c').apply(1)
res2: Char = b

14.

posted @ 2016-07-10 23:11  小样儿1020  阅读(17313)  评论(0编辑  收藏  举报