scala list

目录

创建列表

// String 使用双引号括起来,使用单引号括起来是Char 类型。Char 类型只能是一个字符,String类型是字符串,可以包含多个字符
scala> val s1 : List[String] = List("a","b","c")
s1: List[String] = List(a, b, c)
scala> val s2 : List[String] = List("ab","bc","cd")
s2: List[String] = List(ab, bc, cd)
// List 元素的类型可以省略,scala编译器会自动推导出来
scala> val s2 = List("abcd","cdef","defa")
s2: List[String] = List(abcd, cdef, defa)

// 定义一个字符列表的第3种方法,使用 "::" 构造,需要有Nil 结尾,否则编译器会报错误
scala> val s3 = "Runoob" :: "Google" :: "Baidu" :: Nil
s3: List[String] = List(Runoob, Google, Baidu)

scala> val s4 = "abc" :: "bcd" :: "cde"
<console>:11: error: value :: is not a member of String
       val s4 = "abc" :: "bcd" :: "cde"
                               ^

scala> val c1 : List[Char] = List('d','e','f')
c1: List[Char] = List(d, e, f)

scala> val c2 : List[Char] = List('dr','a','f')
<console>:1: error: ')' expected but character literal found.
val c1 : List[Char] = List('dr','a','f')
                              ^
<console>:1: error: unclosed character literal
val c1 : List[Char] = List('dr','a','f')

// Char 类型也可以使用 "::" 构造,同样以Nil结尾
scala> val c4 = 'a' :: 'b' :: Nil
c4: List[Char] = List(a, b)

scala> val s4 = 'a' :: 'b' :: 'c'
<console>:11: error: value :: is not a member of Char
       val s4 = 'a' :: 'b' :: 'c'
                           ^
                                      ^
// 创建整型列表,创建列表List关键字是无法省略的,除非使用 "::" 构造一个列表
scala> val l1 : List[Int] = List(1,2,3,4)
l1: List[Int] = List(1, 2, 3, 4)

scala> val l2 = List(5,6,7,8)
l2: List[Int] = List(5, 6, 7, 8)

scala> val num2 = 1 :: 2 :: 3 :: Nil
num2: List[Int] = List(1, 2, 3)

// 创建空列表,有一下几种方法
scala> val empty: List[Nothing] = List()
empty: List[Nothing] = List()

scala> val empty1 = List()
empty1: List[Nothing] = List()

// 构造列表的两个基本单位"Nil","::" .Nil 表示一个空列表
scala> val empty2 = Nil
empty2: scala.collection.immutable.Nil.type = List()


// 创建2维列表,多维列表类似
scala> val dim : List[List[Int]] = List(List(1,2,3),List(2,3,4),List(3,4,5))
dim: List[List[Int]] = List(List(1, 2, 3), List(2, 3, 4), List(3, 4, 5))

scala> val dim1 = List(List("key1",123),List("key2",234),List("key3",345))
dim1: List[List[Any]] = List(List(key1, 123), List(key2, 234), List(key3, 345))

scala> val dim2 : List[List[Any]] = List(List("key1",12),List("key2",23),List("key3",34))
dim2: List[List[Any]] = List(List(key1, 12), List(key2, 23), List(key3, 34))


scala> val dim3 : List[List[Any]] = List(List("key1",12,21),List("key2",23,32),List("key3",34,43))
dim3: List[List[Any]] = List(List(key1, 12, 21), List(key2, 23, 32), List(key3, 34, 43))

// [Any] 表示任意类型,任意个数
scala> val dim4 : List[List[Any]] = List(List(12,21),List("key2",23,32,"abc"),List(34,"bcd",43,4.5,3.2F,300000L))
dim4: List[List[Any]] = List(List(12, 21), List(key2, 23, 32, abc), List(34, bcd, 43, 4.5, 3.2, 300000))

// 使用 "::" 和 Nil 可以随意构造2维列表,元素可以不相等,元素的类型也可以按需指定,非常灵活
scala> val dim5 = ("key1",12) :: ("key2",23) :: Nil
dim5: List[(String, Int)] = List((key1,12), (key2,23))

scala> val dim6 = ("abc",12,21) :: ("cde",32,23) :: ("def",45,54) :: Nil
dim5: List[(String, Int, Int)] = List((abc,12,21), (cde,32,23), (def,45,54))

scala> val dim7 = dim5 :: ("efg",43,34) :: Nil
dim6: List[Product with java.io.Serializable] = List(List((abc,12,21), (cde,32,23), (def,45,54)), (efg,43,34))

scala> val dim8 = dim5 :: ("efg",43) :: Nil
dim7: List[Product with java.io.Serializable] = List(List((abc,12,21), (cde,32,23), (def,45,54)), (efg,43))

scala> val dim9 = ("abcef",12,21) :: ("cdegh",32) :: (45,"ef2e",54) :: Nil
dim8: List[Product with Serializable] = List((abcef,12,21), (cdegh,32), (45,ef2e,54))

List 属性

  • List 列表的三属性
    • head 返回第一个元素
    • tail 返回除了第一个元素以外的其他所有元素
    • isEmpty 在列表为空时返回true
scala> dim1
res3: List[List[Any]] = List(List(key1, 123), List(key2, 234), List(key3, 345))


scala> dim1.head
res0: List[Any] = List(key1, 123)

scala> dim1.tail
res2: List[List[Any]] = List(List(key2, 234), List(key3, 345))


scala> empty.isEmpty
res4: Boolean = true

scala> dim1.isEmpty
res5: Boolean = false

列表的连接

  • 列表的连接。列出了3种方法
object listConcat {
    def main(args : Array[String]) {
        val site1 = "Runoob" :: ("Google" :: ("Baidu" :: Nil))
        val site2 = "Facebook" :: ("Taobao" :: Nil)

        // :::
        val fruit = site1 ::: site2
        println("site1: " + site1)
        println("site2: " + site2)
        println("site1 ::: site2 : " + fruit)

        // Set.:::()
        val fruit1 = site1.:::(site2)
        println("site1: ",site1)
        println("site2: ",site2)
        println("site1.:::(site2) :" + fruit1)

        // concat()
        val fruit2 = List.concat(site1,site2)
        println("List.concat(site1,site2) :" + fruit2)
    }
}

/*
output:
site1: List(Runoob, Google, Baidu)
site2: List(Facebook, Taobao)
site1 ::: site2 : List(Runoob, Google, Baidu, Facebook, Taobao)
(site1: ,List(Runoob, Google, Baidu))
(site2: ,List(Facebook, Taobao))
site1.:::(site2) :List(Facebook, Taobao, Runoob, Google, Baidu)
List.concat(site1,site2) :List(Runoob, Google, Baidu, Facebook, Taobao)
*/

scala> List(1,2,3,4).:::(List("a","b"))
res3: List[Any] = List(a, b, 1, 2, 3, 4)
/*
list1.:::(list2) 这种方式有些特别,list2的元素按原顺序排在前面,紧接着
是list1的元素,同样是按照原顺序排在后面
list1:::list2  和 List.concat(list1,list2) 这两种方法所得到的效果一样,
list1 的元素在前,list2 的元素在后
 */

fill() 创建多个重复的元素

  • 使用List.fill() 创建多个重复的元素
object listFill {
    def main(args : Array[String]) {
        val site = List.fill(3)(123)
        val site1 = List.fill(4)("abc")
        val site2 = List.fill(5)("abc","cde")
        val site3 = List.fill(5)(Nil)
        val site4 = List.fill(5)("")
        val site5 = List.fill(5)(List(1,2,3,4))
        println("site: " + site)
        println("site1: " + site1)
        println("site2: " + site2)
        println("site3: " + site3)
        println("site4: " + site4)
        println("site5: " + site5)
    }
}
/*
先编译
[root@master list]# scalac fill.scala
然后运行编译后产生的字节码文件
[root@master list]# scala listFill
site: List(123, 123, 123)
site1: List(abc, abc, abc, abc)
site2: List((abc,cde), (abc,cde), (abc,cde), (abc,cde), (abc,cde))
site3: List(List(), List(), List(), List(), List())
site4: List(, , , , )
site5: List(List(1, 2, 3, 4), List(1, 2, 3, 4), List(1, 2, 3, 4), List(1, 2, 3, 4), List(1, 2, 3, 4))

运行6次就产生了6个listFill$$anonfun$*.class 这样的文件
[root@master list]# ll
total 36
-rw-r--r-- 1 root root  517 Apr 11 20:09 fill.scala
-rw-r--r-- 1 root root  891 Apr 11 20:09 listFill$$anonfun$1.class
-rw-r--r-- 1 root root  830 Apr 11 20:09 listFill$$anonfun$2.class
-rw-r--r-- 1 root root 1013 Apr 11 20:09 listFill$$anonfun$3.class
-rw-r--r-- 1 root root  945 Apr 11 20:09 listFill$$anonfun$4.class
-rw-r--r-- 1 root root  827 Apr 11 20:09 listFill$$anonfun$5.class
-rw-r--r-- 1 root root 1249 Apr 11 20:09 listFill$$anonfun$6.class
-rw-r--r-- 1 root root  570 Apr 11 20:09 listFill.class
-rw-r--r-- 1 root root 1751 Apr 11 20:09 listFill$.class
[root@master list]# file -i listFill.class
listFill.class: application/x-java-applet; charset=binary

*/

List.tabulate() 创建列表

  • List.tabulate() 创建列表,和List.fill() 所不同的是List中的元素是由另一个函数计算得出的,而List.full() List中的元素是人为手动给的
object tabulate {
    def main(args: Array[String]) {
        val squares = List.tabulate(6)(n => n *n)
        println("a one-dimensiona: " + squares)

        val mul = List.tabulate(4,5)(_*_)
        println("multidimensional: " + mul)
    }
}

/*
output:
a one-dimensiona: List(0, 1, 4, 9, 16, 25)
multidimensional: List(List(0, 0, 0, 0, 0), List(0, 1, 2, 3, 4), List(0, 2, 4, 6, 8), List(0, 3, 6, 9, 12))

解释下 (_*_) 就是"行*列"的意思
scala> List.tabulate(2,2)(_*_)
res27: List[List[Int]] = List(List(0, 0), List(0, 1))

scala> List.tabulate(2,2)((row: Int,col: Int) => row * col)
res28: List[List[Int]] = List(List(0, 0), List(0, 1))
*/

reverse 列表反转

  • List.reverse 列表反转,只是将原来的顺序倒过来,没有排序

scala> List(1,2,3,4,5,6).reverse
res33: List[Int] = List(6, 5, 4, 3, 2, 1)

scala> List(3,4,2,5,1,6,4,2).reverse
res34: List[Int] = List(2, 4, 6, 1, 5, 2, 4, 3)

列表常用函数

“+:” 像列表前面预添加元素

  • +: 向列表中预添加元素,添加在列表的最前面。记住并不是真的向列表中添加,原列表的内容不变,只是预演一下,当然可以产生一个新的列表。无论当前列表是var还是val,列表都是不变的
  • item +: list 不能反过来
scala> var x = List(1,2,3)
x: List[Int] = List(1, 2, 3)

scala> 4 +: x
res38: List[Int] = List(4, 1, 2, 3)

scala> x
res39: List[Int] = List(1, 2, 3)


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

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

scala> x :: 2
<console>:13: error: value :: is not a member of Int
       x :: 2
         ^


scala> x +: 4
<console>:13: error: value +: is not a member of Int
       x +: 4
         ^

“::” 和”+:” 效果一样

  • item :: List 在列表的前面添加元素,和 “+:” 效果一样。原列表并没有发生变化,可以产生新的列表
  • list1 :: list2
scala> var x = List(1,2,3,4)
x: List[Int] = List(1, 2, 3, 4)
scala> (2)::x
res2: List[Int] = List(2, 1, 2, 3, 4)

scala> 2 :: x
res3: List[Int] = List(2, 1, 2, 3, 4)
scala> x
res4: List[Int] = List(1, 2, 3, 4)

scala> x :: 2
<console>:13: error: value :: is not a member of Int
       x :: 2
         ^

“:::” list1 ::: list2

  • list1 ::: list2 将list2 中的元素按原顺序、追加至list1后面,list1,list2 这两个列表均不变
scala> val x = List(3,4,5,6)
res4: List[Int] = List(1, 2, 3, 4)

scala> var y = List(3,4,5,6)
y: List[Int] = List(3, 4, 5, 6)

scala> x ::: y
res23: List[Int] = List(1, 2, 3, 4, 3, 4, 5, 6)

scala> x
res24: List[Int] = List(1, 2, 3, 4)

scala> y
res25: List[Int] = List(3, 4, 5, 6)

scala> x +: y
res26: List[Any] = List(List(1, 2, 3, 4), 3, 4, 5, 6)

scala> x :: y
res27: List[Any] = List(List(1, 2, 3, 4), 3, 4, 5, 6)

// ":::" 前后都是list
scala> b
res14: List[String] = List(Leo, Jack, Jen)

scala> 1 ::: b
<console>:13: error: type mismatch;
 found   : Int
 required: List[?]
       1 ::: b
         ^

“:+” : list :+ item list 和 item 顺序不能反过来

  • list :+ item
scala> x
res38: List[Int] = List(1, 2, 3, 4)

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

addString 函数,返回StringBuilder

  • list.addString(b:StringBuilder) 将List中的元素按顺序添加至b中,b为StringBuilder,b的值发生变化,StringBuilder 为可变序列
scala> val s = new StringBuilder("abc")
s: StringBuilder = abc

scala> x.addString(s)
res48: StringBuilder = abc1234

scala> x
res49: List[Int] = List(1, 2, 3, 4)

scala> s
res50: StringBuilder = abc1234

scala> val s1 = new StringBuilder("cde")
s1: StringBuilder = cde

// "-" 指定列表元素之间的分隔符。这个需要自定义,默认分隔符为空
scala> x.addString(s1,"-")
res56: StringBuilder = cde1-2-3-4

scala> s1
res57: StringBuilder = cde1-2-3-4

apply() 函数,获取item的index

  • list.apply(item) 通过索引获取列表中的元素,索引从0开始
scala> x
res58: List[Int] = List(1, 2, 3, 4)

scala> x.apply(2)
res60: Int = 3

scala> x.apply(1)
res61: Int = 2


scala> val y = List(1,2,6,3,1,2,7,2,4,5)
y: List[Int] = List(1, 2, 6, 3, 1, 2, 7, 2, 4, 5)

scala> y.apply(2)
res65: Int = 6

list.contains(item) 如果item 存在于list中就返回True,否则返回false

scala> y
res82: List[Int] = List(1, 2, 6, 3, 1, 2, 7, 2, 4, 5)

scala> y.contains(2)
res83: Boolean = true

scala> y.contains(8)
res84: Boolean = false

list.copyToArray(a: Array,start: Int,len: Int)

  • 参数 a 是一个数组
  • start Int 类型表示数组的索引
  • len Int 类型,表示长度
  • 这个函数的作用:在数组a中从索引start位置开始将列表list中的元素(从索引0开始),替换数组中的元素,按顺序替换,替换长度是len
scala> var a = Array(5,6,7,7,0,12,9,21,18)
a: Array[Int] = Array(5, 6, 7, 7, 0, 12, 9, 21, 18)

scala> x.copyToArray(a,2,4)

scala> a
res101: Array[Int] = Array(5, 6, 1, 2, 3, 4, 9, 21, 18)

scala> var a = Array(5,6,7,7,0,12,9,21,18)
a: Array[Int] = Array(5, 6, 7, 7, 0, 12, 9, 21, 18)

scala> x.copyToArray(a,1,3)

scala> a
res103: Array[Int] = Array(5, 1, 2, 3, 0, 12, 9, 21, 18)


scala> a
res105: Array[Any] = Array(5, 1, 2, 3, 4, 12, abc, 2.3, 3, 2.0, 25000, 9, 21, 18)

scala> var a = Array(5,6,7,7,0,12,"abc",2.3,3,2F,25000L,9,21,18)
a: Array[Any] = Array(5, 6, 7, 7, 0, 12, abc, 2.3, 3, 2.0, 25000, 9, 21, 18)

scala> x.copyToArray(a,4,6)

scala> a
res107: Array[Any] = Array(5, 6, 7, 7, 1, 2, 3, 4, 3, 2.0, 25000, 9, 21, 18)

scala> val a = Array(5,6,7,7,0,12,"abc",2.3,3,2F,25000L,9,21,18)
a: Array[Any] = Array(5, 6, 7, 7, 0, 12, abc, 2.3, 3, 2.0, 25000, 9, 21, 18)

// 虽然a是val不可变类型,但是这里的a还是发生了变化
scala> x.copyToArray(a,4,6)

scala> a
res109: Array[Any] = Array(5, 6, 7, 7, 1, 2, 3, 4, 3, 2.0, 25000, 9, 21, 18)

list.distinct 消除列表重复的值

  • 注意这里的值应该是同类型的,如果不同的类型值肯定不一样,尽管打印出来表现得一样
scala> y
res110: List[Int] = List(1, 2, 6, 3, 1, 2, 7, 2, 4, 5)

scala> y.distinct
res111: List[Int] = List(1, 2, 6, 3, 7, 4, 5)

scala> val a = List(1,2,"12",12,"123",123,"1234",1234,2,12,123,1234)
a: List[Any] = List(1, 2, 12, 12, 123, 123, 1234, 1234, 2, 12, 123, 1234)

scala> a.distinct
res112: List[Any] = List(1, 2, 12, 12, 123, 123, 1234, 1234)

/* 
2D2F 是一样的
22L 是一样的
12.34D12.34F 不是一样的
*/
scala> val a = List(1,2,"12",12,"123",123,"1234",1234,2,12,123,1234,12.34D,12.34F,2L,2F,2D)
a: List[Any] = List(1, 2, 12, 12, 123, 123, 1234, 1234, 2, 12, 123, 1234, 12.34, 12.34, 2, 2.0, 2.0)

scala> a.distinct
res117: List[Any] = List(1, 2, 12, 12, 123, 123, 1234, 1234, 12.34, 12.34, 2.0)

drop 和 dropRight 丢弃一些元素生成新的列表,原列表保持不变

  • def List[Any].drop(n: Int) : List[Any] 丢弃列表中前n个元素,生成一个新列表,但是原列表的值不变
  • def List[Any].dropRight(n: Int) 删除最后n个元素,生成一个新的列表,原列表保持不变
scala> var b = List(2,32,12,34,54,12,2,4,9,0)
b: List[Int] = List(2, 32, 12, 34, 54, 12, 2, 4, 9, 0)

scala> b.drop(5)
res121: List[Int] = List(12, 2, 4, 9, 0)

scala> b
res122: List[Int] = List(2, 32, 12, 34, 54, 12, 2, 4, 9, 0)

scala> val a = List(1,2,"12",12,"123",123,"1234",1234,2,12,123,1234,12.34D,12.34F,2L,2F,2D)
a: List[Any] = List(1, 2, 12, 12, 123, 123, 1234, 1234, 2, 12, 123, 1234, 12.34, 12.34, 2, 2.0, 2.0)

scala> a.drop(8)
res123: List[Any] = List(2, 12, 123, 1234, 12.34, 12.34, 2, 2.0, 2.0)

scala> a
res124: List[Any] = List(1, 2, 12, 12, 123, 123, 1234, 1234, 2, 12, 123, 1234, 12.34, 12.34, 2, 2.0, 2.0)

scala> val x = List("a","b","c","d")
x: List[String] = List(a, b, c, d)

scala> x.dropRight(2)
res2: List[String] = List(a, b)

scala> x
res3: List[String] = List(a, b, c, d)

// 当 n > list.length,返回一个空列表,不报错
scala> x.drop(6)
res6: List[String] = List()

scala> x.dropRight(8)
res7: List[String] = List()

// 无论 list 是var还是val类型,原列表的值总是保持不变
scala> var y = List(1,2,6,3,2,6,3,2,10,32)
y: List[Int] = List(1, 2, 6, 3, 2, 6, 3, 2, 10, 32)

scala> y.drop(5)
res9: List[Int] = List(6, 3, 2, 10, 32)

scala> y
res10: List[Int] = List(1, 2, 6, 3, 2, 6, 3, 2, 10, 32)

scala> y.dropRight(5)
res11: List[Int] = List(1, 2, 6, 3, 2)

scala> y
res12: List[Int] = List(1, 2, 6, 3, 2, 6, 3, 2, 10, 32)

list.dropWhile(expression p)

  • 从左至右删除列表中的元素,直到表达式p(逻辑表达式)返回false,停止删除元素
  • 这里有点类似while的循环条件,一旦不满足循环条件,循环就结束,同理p表达式返回false,不再删除列表中的元素。原列表保持不变,生成一个新的列表

scala> val p = 5
p: Int = 5

scala> y
res15: List[Int] = List(1, 2, 6, 3, 2, 6, 3, 2, 10, 32)

// 如果第1个元素作用于表达式返回false,一个元素都不删除
scala> y.dropWhile(x => x >p)
res16: List[Int] = List(1, 2, 6, 3, 2, 6, 3, 2, 10, 32)

scala> y.dropWhile(x => x < 4)
res20: List[Int] = List(6, 3, 2, 6, 3, 2, 10, 32)

scala> y
res22: List[Int] = List(1, 2, 6, 3, 2, 6, 3, 2, 10, 32)

scala> val z = List(6,0,21,83,20,12,3,2,5)
z: List[Int] = List(6, 0, 21, 83, 20, 12, 3, 2, 5)

scala> z.dropWhile(x => x > 4)
res21: List[Int] = List(0, 21, 83, 20, 12, 3, 2, 5)


scala> z
res23: List[Int] = List(6, 0, 21, 83, 20, 12, 3, 2, 5)

def endsWithB : Boolean 判断列表是否以制定的序列结尾

scala> y
res24: List[Int] = List(1, 2, 6, 3, 2, 6, 3, 2, 10, 32)

scala> val b = Seq(2,10,32)
b: Seq[Int] = List(2, 10, 32)

scala> y.endsWith(b)
res27: Boolean = true

scala> y.endsWith(Seq(2,10,32))
res28: Boolean = true

scala> y.endsWith(Seq(2,5,32))
res29: Boolean = false

def equals(that: Any) : Boolean

  • 虽然that 是任意类型,但是that 需要是以下类型,并且值相等才能返回true 否则返回false
    • List,Seq,Vector
scala> y
res30: List[Int] = List(1, 2, 6, 3, 2, 6, 3, 2, 10, 32)

scala> y.equals(2)
res31: Boolean = false

scala> y.equals(3)
res32: Boolean = false

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

scala> y.equals(a)
res33: Boolean = true

scala> val b = Seq(1, 2, 6, 3, 2, 6, 3, 2, 10, 32)
b: Seq[Int] = List(1, 2, 6, 3, 2, 6, 3, 2, 10, 32)

scala> y.equals(b)
res34: Boolean = true

scala> val c = Vector(1, 2, 6, 3, 2, 6, 3, 2, 10, 32)
c: scala.collection.immutable.Vector[Int] = Vector(1, 2, 6, 3, 2, 6, 3, 2, 10, 32)

scala> y.equals(c)
res35: Boolean = true

scala> val d = Array(1, 2, 6, 3, 2, 6, 3, 2, 10, 32)
d: Array[Int] = Array(1, 2, 6, 3, 2, 6, 3, 2, 10, 32)

scala> y.equals(d)
res36: Boolean = false

scala> val e = Set(1, 2, 6, 3, 2, 6, 3, 2, 10, 32)
e: scala.collection.immutable.Set[Int] = Set(10, 1, 6, 2, 32, 3)

scala> y.equals(e)
res37: Boolean = false

scala> val f = Map("one" -> 1,"two" -> 2,"three" -> 6,"four" -> 3,"fire" -> 2,"six" -> 6,"seven" -> 3, "eight" -> 2,"nine" -> 10, "ten" -> 32)
f: scala.collection.immutable.Map[String,Int] = Map(four -> 3, fire -> 2, three -> 6, two -> 2, six -> 6, seven -> 3, ten -> 32, nine -> 10, one -> 1, eight -> 2)

scala> y.equals(f)
res38: Boolean = false

def exists (x => x == List(item)) : Boolean 判断某个元素是否存在于列表中

scala> y
res39: List[Int] = List(1, 2, 6, 3, 2, 6, 3, 2, 10, 32)

scala> y.exists( x=> x == 2)
res41: Boolean = true

scala> y.exists( x=> x == 5)
res42: Boolean = false

scala> y.exists( x=> x == 8)
res43: Boolean = false

scala> y.exists( x=> x == 10)
res44: Boolean = true

def filter(x => x experssion) :Boolean

  • x为列表中的某个元素,含x的逻辑表达式。过滤列表中的元素,返回满足条件的元素,组成一个新的列表。原列表不变
scala> y
res46: List[Int] = List(1, 2, 6, 3, 2, 6, 3, 2, 10, 32)

scala> y.filter(x=> x > 5)
res47: List[Int] = List(6, 6, 10, 32)

scala> val z = List("abcde","fgh","hijklmn","wert")
z: List[String] = List(abcde, fgh, hijklmn, wert)

scala> z.filter( x=> x.length >3)
res48: List[String] = List(abcde, hijklmn, wert)

scala> z.filter(s => s.startsWith("h"))
res50: List[String] = List(hijklmn)

// 区分大小写,没有匹配的条件就输出空列表
scala> z.filter(s => s.startsWith("H"))
res51: List[String] = List()

def foreach(f: (A) => Unit): Uni

  • foreach 遍历列表中所有的元素,将所有的元素应用于f 函数。这里省略使用循环遍历列表中所有的元素
scala> x
res61: List[Int] = List(3, 9, 10, 23, 43, 12, 34)

scala> x.foreach(println(_))
3
9
10
23
43
12
34

scala> x.foreach(x => x + 1)

scala> x foreach(x => println(x+1))
4
10
11
24
44
13
35

// map 有返回值,而且返回的类型同样是list。
scala> x.map(x=> x+1)
res65: List[Int] = List(4, 10, 11, 24, 44, 13, 35)

def forall(x => x experssion) :Boolean

  • x(列表中所有的元素) 逻辑表达式,将列表中所有的元素应用于逻辑表达式,只有所有的元素在此逻辑表达式都返回true,函数才返回true,否则返回false
scala> val x = List(32,9,20,31,10,18,16)
x: List[Int] = List(32, 9, 20, 31, 10, 18, 16)

scala> x.forall(x => x > 5)
res0: Boolean = true

scala> x.forall(x => x > 15)
res1: Boolean = false

scala> x.forall(x => x > 9)
res2: Boolean = false

scala> x.forall(x => x > 8)
res3: Boolean = true

scala> x.forall(x => x >= 9)
res4: Boolean = true

scala> x.forall(x => x >= 10)
res5: Boolean = false

scala> val y = List("Hello python","Hello scala","Hello java","Hello spark")
y: List[String] = List(Hello python, Hello scala, Hello java, Hello spark)

scala> y.forall(s => s.startsWith("H"))
res6: Boolean = true

scala> y.forall(s => s.startsWith("Hello"))
res7: Boolean = true

scala> y.forall(s => s.startsWith("hello"))
res8: Boolean = false

list.head 返回列表中的第一个元素

scala> y
res11: List[String] = List(Hello python, Hello scala, Hello java, Hello spark)

scala> x
res12: List[Int] = List(32, 9, 20, 31, 10, 18, 16)

scala> y.head
res9: String = Hello python

scala> x.head
res10: Int = 32

scala> val a = List(List(23,32,20),List("abc","cde","qwe"),List(14,36,23))
a: List[List[Any]] = List(List(23, 32, 20), List(abc, cde, qwe), List(14, 36, 23))

scala> a.head
res13: List[Any] = List(23, 32, 20)

def indexOf(item: A,from : Int) : Int

  • 从from 位置开始搜索item第一次出现的位置。求索引,只是索引起始值可以自定义,并不一定要从0开始
    • item: 列表中某一个元素
    • from:从什么位置开始,搜索。如果此参数省略表示从0开始
scala> val x = List(20,13,20,13,16,17,18,13,20,13,20)
x: List[Int] = List(20, 13, 20, 13, 16, 17, 18, 13, 20, 13, 20)

scala> x.indexOf(20)
res16: Int = 0

scala> x.indexOf(20,3)
res17: Int = 8

scala> x.indexOf(20,1)
res18: Int = 2

list.inti :List 返回除最后一个元素的所有元素,生成一个新列表,原列表不变

scala> var y = List(23,91,20,10,23,11,18)
y: List[Int] = List(23, 91, 20, 10, 23, 11, 18)

scala> y.init
res22: List[Int] = List(23, 91, 20, 10, 23, 11)

scala> y
res23: List[Int] = List(23, 91, 20, 10, 23, 11, 18)

scala> val x = List(20, 13, 20, 13, 16, 17, 18, 13, 20, 13, 20)
x: List[Int] = List(20, 13, 20, 13, 16, 17, 18, 13, 20, 13, 20)

scala> x.init
res24: List[Int] = List(20, 13, 20, 13, 16, 17, 18, 13, 20, 13)

scala> x
res25: List[Int] = List(20, 13, 20, 13, 16, 17, 18, 13, 20, 13, 20)

def intersect(that: Seq[A]) : List[A] 求两个集合的交集,不考虑元素的顺序

scala> val x = List(12,32,30,18,27,9,11)
x: List[Int] = List(12, 32, 30, 18, 27, 9, 11)

scala> val y = List(12,32,30,45,17,9,11)
y: List[Int] = List(12, 32, 30, 45, 17, 9, 11)

scala> x.intersect(y)
res27: List[Int] = List(12, 32, 30, 9, 11)


scala> x
res28: List[Int] = List(12, 32, 30, 18, 27, 9, 11)

// 两list 中的元素的顺序不需要一致,只要都包含此元素就会返回此元素,组成一个新列表
scala> x.intersect(List(2,3,30,14,9,20,12,30,18,11))
res29: List[Int] = List(12, 30, 18, 9, 11)

scala> x.intersect(Seq(12,9,20,30,18,27))
res30: List[Int] = List(12, 30, 18, 27, 9)

scala> x.intersect(Seq(12,9,20,30,18,27))
res30: List[Int] = List(12, 30, 18, 27, 9)

scala> x.intersect(Array(12,8,3,28,30))
res31: List[Int] = List(12, 30)

scala> x.intersect(Vector(28,34,26,14))
res32: List[Int] = List()

scala> x.intersect(Vector(27,34,26,18))
res33: List[Int] = List(18, 27)

//  不支持 list 和tuple 求交集
scala> val b = Tuple7(2,3,10,20,12,18,30)
b: (Int, Int, Int, Int, Int, Int, Int) = (2,3,10,20,12,18,30)

scala> b
res37: (Int, Int, Int, Int, Int, Int, Int) = (2,3,10,20,12,18,30)

scala> x.intersect(b)
<console>:14: error: type mismatch;
 found   : (Int, Int, Int, Int, Int, Int, Int)
 required: scala.collection.GenSeq[?]
       x.intersect(b)
                   ^

def iterator: Iterator[A] 创建一个新的迭代器

scala> x.iterator
res40: Iterator[Int] = non-empty iterator

scala> x iterator
warning: there was one feature warning; re-run with -feature for details
res41: Iterator[Int] = non-empty iterator

scala> val b = x.iterator
b: Iterator[Int] = non-empty iterator

scala> b
res42: Iterator[Int] = non-empty iterator

scala> b.foreach(println(_))
12
32
30
18
27
9
11

scala> x
res44: List[Int] = List(12, 32, 30, 18, 27, 9, 11)

def last :A 返回列表中最后一个元素

scala> x
res44: List[Int] = List(12, 32, 30, 18, 27, 9, 11)

scala> x.last
res45: Int = 11

def lastIndexOf(item: A ,end : Int) : Int

  • 从end位置开始搜索item最后一次出现的位置。这里的最后一次出现的位置并不是离列表的尾部最近的位置,有可能走完列表的最尾部还返回到列表的最前面继续查找,最终得到最后的位置
    • item : 列表中的元素
    • end: 从什么位置开始搜索,如果此参数不给就列表中最后一次出现此元素的索引

这里写图片描述

scala> val x = List(34,12,32,34,90,29,34,12,34,34,32,31,36)
x: List[Int] = List(34, 12, 32, 34, 90, 29, 34, 12, 34, 34, 32, 31, 36)

scala> x.lastIndexOf(34)
res49: Int = 9

scala> x.lastIndexOf(34,3)
res50: Int = 3

scala> x.lastIndexOf(34,1)
res51: Int = 0

scala> x.lastIndexOf(34,4)
res52: Int = 3

scala> x.lastIndexOf(34,10)
res53: Int = 9

scala> x.lastIndexOf(34,11)
res54: Int = 9


scala> x.lastIndexOf(34,15)
res57: Int = 9

// end > list.length 不会报错
scala> x.lastIndexOf(34,30)
res58: Int = 9

def length : Int 求列表的长度

scala> x.length
res59: Int = 13

scala> x
res60: List[Int] = List(34, 12, 32, 34, 90, 29, 34, 12, 34, 34, 32, 31, 36)

def map[B](f: (A) => B): List[B] 将列表中的每一个元素应用于函数f,并返回一个新的列表。原列表保持不变

scala> x
res60: List[Int] = List(34, 12, 32, 34, 90, 29, 34, 12, 34, 34, 32, 31, 36)

scala> x.map(x => x * 2)
res61: List[Int] = List(68, 24, 64, 68, 180, 58, 68, 24, 68, 68, 64, 62, 72)

scala> def square(a :Int): Int = a * a
square: (a: Int)Int

scala> x
res62: List[Int] = List(34, 12, 32, 34, 90, 29, 34, 12, 34, 34, 32, 31, 36)

scala> x.map(x => square(x))
res63: List[Int] = List(1156, 144, 1024, 1156, 8100, 841, 1156, 144, 1156, 1156, 1024, 961, 1296)

scala> x
res64: List[Int] = List(34, 12, 32, 34, 90, 29, 34, 12, 34, 34, 32, 31, 36

max,min 函数

  • def max :A 返回列表中值最大的元素
  • def min :A 返回列表中值最的小元素
  • 字符串之间的比较,只比较首字母对应的ascII的值
  • Double,Float,Int之间的比较哈斯按照常规的数学世界的比较,只单纯的比较值的大小
scala> x
res64: List[Int] = List(34, 12, 32, 34, 90, 29, 34, 12, 34, 34, 32, 31, 36)

scala> x.max
res65: Int = 90

scala> x
res66: List[Int] = List(34, 12, 32, 34, 90, 29, 34, 12, 34, 34, 32, 31, 36)

scala> x.min
res67: Int = 12

scala> val y = List("abc","cde","def","art")
y: List[String] = List(abc, cde, def, art)

scala> y.max
res68: String = def

scala> y.min
res69: String = abc

scala> val y = List("abc","cde","def","ayz")
y: List[String] = List(abc, cde, def, ayz)

scala> y.max
res70: String = def

scala> y.min
res71: String = abc

scala> val y = List("abc","cde","dab","ayz")
y: List[String] = List(abc, cde, dab, ayz)

scala> y.max
res72: String = dab

scala> y.min
res73: String = abc

scala> val y = List("abc","cde","daa","azz")
y: List[String] = List(abc, cde, daa, azz)

scala> y.max
res74: String = daa

scala> y.min
res75: String = abc

scala> val y = List("abc","cde","daa","Azz")
y: List[String] = List(abc, cde, daa, Azz)

scala> y.max
res76: String = daa

scala> y.min
res77: String = Azz

scala> val y = List("abc","cde","Daa","Azz")
y: List[String] = List(abc, cde, Daa, Azz)

scala> y.max
res78: String = cde

scala> y.min
res79: String = Azz

scala> val x = List(5,3.4D,3.5F,6L,7)
x: List[Double] = List(5.0, 3.4, 3.5, 6.0, 7.0)

scala> x.max
res85: Double = 7.0

scala> x.min
res86: Double = 3.4

scala> val x = List(5,3.4D,3.2F,6L,7)
x: List[Double] = List(5.0, 3.4, 3.200000047683716, 6.0, 7.0)

scala> x.max
res87: Double = 7.0

scala> x.min
res88: Double = 3.200000047683716

def mkString(sep: String): String 所有的元素以字符串显示

  • seq : 分隔符,可以省略。默认是 “”
scala> val x = List(1,3,2,3,6,10,20,13,23)
x: List[Int] = List(1, 3, 2, 3, 6, 10, 20, 13, 23)

scala> x.mkString
res90: String = 1323610201323

scala> x.mkString("-")
res91: String = 1-3-2-3-6-10-20-13-23

scala> val y = List("abc","cde","efg","hijk")
y: List[String] = List(abc, cde, efg, hijk)

scala> y.mkString
res92: String = abccdeefghijk

scala> y.mkString(",")
res93: String = abc,cde,efg,hijk

scala> y.mkString(".")
res94: String = abc.cde.efg.hijk

scala> x
res97: List[Int] = List(1, 3, 2, 3, 6, 10, 20, 13, 23)

scala> val b = x.toString
b: String = List(1, 3, 2, 3, 6, 10, 20, 13, 23)

scala> b
res98: String = List(1, 3, 2, 3, 6, 10, 20, 13, 23)

scala> x foreach print
1323610201323
scala> x
res105: List[Int] = List(1, 3, 2, 3, 6, 10, 20, 13, 23)

//  list.toString 列表转换成String,但是会将List这个关键字带上,一般情况下,这个关键字对于转换成字符串是没有意义的
scala> b foreach print
List(1, 3, 2, 3, 6, 10, 20, 13, 23)
scala> b
res107: String = List(1, 3, 2, 3, 6, 10, 20, 13, 23)

def startsWith[B](that: Seq[B], offset: Int): Boolean

  • that类型: Seq,List,Array,Vector, 不支持Set,和Iterator
scala> x
res108: List[Int] = List(1, 3, 2, 3, 6, 10, 20, 13, 23)

scala> x.startsWith(Seq(1,2))
res109: Boolean = false

scala> x.startsWith(Seq(1,3))
res110: Boolean = true

scala> x.startsWith(Seq(1,3,4))
res111: Boolean = false

scala> x.startsWith(Seq(1,3,2))
res112: Boolean = true

scala> x.startsWith(List(1,3,2))
res113: Boolean = true

scala> x.startsWith(Array(1,3,2))
res114: Boolean = true

scala> x.startsWith(Vector(1,3,2))
res115: Boolean = true

scala> val b = List(1,3,2).iterator
b: Iterator[Int] = non-empty iterator

scala> x.startsWith(b)
<console>:14: error: type mismatch;
 found   : Iterator[Int]
 required: scala.collection.GenSeq[?]
       x.startsWith(b)
                    ^

scala> x.startsWith(Set(1,3,2))
<console>:13: error: type mismatch;
 found   : scala.collection.immutable.Set[Int]
 required: scala.collection.GenSeq[?]
       x.startsWith(Set(1,3,2))

scala> val x = List(32,12,25,13,90,36,33,12,25,13,87,46,12,25,13)
x: List[Int] = List(32, 12, 25, 13, 90, 36, 33, 12, 25, 13, 87, 46, 12, 25, 13)

scala> x.startsWith(List(12,25,13))
res125: Boolean = false

scala> x.startsWith(List(12,25,13),1)
res126: Boolean = true

scala> x.startsWith(List(12,25,13),7)
res127: Boolean = true

scala> x.startsWith(List(12,25,13),12)
res128: Boolean = true

scala> x.startsWith(List(12,25,13),13)
res129: Boolean = false

def sum :A 列表中所有的元素求和

scala> x.sum
res130: Int = 474

scala> x
res131: List[Int] = List(32, 12, 25, 13, 90, 36, 33, 12, 25, 13, 87, 46, 12, 25, 13)

scala> 32 + 12 + 25 + 13 + 90 + 36 + 33 + 12 + 25 + 13 + 87 + 46 + 12 + 25 + 13
res132: Int = 474

// List[String]类型不支持使用sum 这个函数
scala> val b = List("aed","erf","wer")
b: List[String] = List(aed, erf, wer)

scala> b.sum
<console>:13: error: could not find implicit value for parameter num: Numeric[String]
       b.sum
         ^

take,takeRight 函数

  • def take(n: Int): List[A] 提取前n个元素
  • def takeRight(n: Int): List[A] 提取后n个元素
scala> x
res134: List[Int] = List(32, 12, 25, 13, 90, 36, 33, 12, 25, 13, 87, 46, 12, 25, 13)


// 提取前 n 个
scala> x.takeRight(5)
res136: List[Int] = List(87, 46, 12, 25, 13)

//  提取后 n 个
scala> x.take(5)
res137: List[Int] = List(32, 12, 25, 13, 90)

和其他序列之间的转换

  • toArray
  • toSEq
  • toSEt
  • toBuufer
  • toMap
  • toString
scala> x
res153: List[Int] = List(32, 12, 25, 13, 90, 36, 33, 12, 25, 13, 87, 46, 12, 25, 13)

scala> x.toArray
res138: Array[Int] = Array(32, 12, 25, 13, 90, 36, 33, 12, 25, 13, 87, 46, 12, 25, 13)

scala> x.toBuffer
res139: scala.collection.mutable.Buffer[Int] = ArrayBuffer(32, 12, 25, 13, 90, 36, 33, 12, 25, 13, 87, 46, 12, 25, 13)

scala> x.toSet
res154: scala.collection.immutable.Set[Int] = Set(25, 46, 33, 13, 32, 12, 87, 36, 90)

scala> val a = List(("Leo",80),("jack",100),("Jen",90))
a: List[(String, Int)] = List((Leo,80), (jack,100), (Jen,90))

scala> a.toMap
res1: scala.collection.immutable.Map[String,Int] = Map(Leo -> 80, jack -> 100, Jen -> 90)

scala> val b = List("Leo","Jack","Jen")
b: List[String] = List(Leo, Jack, Jen)

scala> val c = List(80,100,90)
c: List[Int] = List(80, 100, 90)

scala> val d = b.zip(c)
d: List[(String, Int)] = List((Leo,80), (Jack,100), (Jen,90))

scala> d
res2: List[(String, Int)] = List((Leo,80), (Jack,100), (Jen,90))

scala> d.toMap
res3: scala.collection.immutable.Map[String,Int] = Map(Leo -> 80, Jack -> 100, Jen -> 90)

scala> b
res20: List[String] = List(Leo, Jack, Jen)

scala> b.toString
res21: String = List(Leo, Jack, Jen)

zip 函数。将两个列表中的元素(x,y)合并成一个pair数组,生成一个新的数组

scala> b
res5: List[String] = List(Leo, Jack, Jen)

scala> val c = List(80,100,90,30)
c: List[Int] = List(80, 100, 90, 30)

scala> b.zip(c)
res6: List[(String, Int)] = List((Leo,80), (Jack,100), (Jen,90))

scala> c.zip(b)
res7: List[(Int, String)] = List((80,Leo), (100,Jack), (90,Jen))
阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/jslijb/article/details/79947726
文章标签: scala list 基础
个人分类: scala 基础
上一篇scala 程序设计之函数式编程
下一篇scala Array 介绍
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭