scala集合三大类(seq序列,set集,map映射)
seq序列:
scala> val list1 = List(1,2,3)
list1: List[Int] = List(1, 2, 3)
scala> val list2 = 0 :: list1
list2: List[Int] = List(0, 1, 2, 3)
//下面两个方式效果一样, :: and +:
scala> val list3 = list1.::(0)
list3: List[Int] = List(0, 1, 2, 3)
scala> val list4 = 0 +: list1
list4: List[Int] = List(0, 1, 2, 3)
scala> val list5 = list1.+:(0)
list5: List[Int] = List(0, 1, 2, 3)
scala> val list5 = list1.+:(0)
list5: List[Int] = List(0, 1, 2, 3)
scala> val list6 = list1 :+ 4
list6: List[Int] = List(1, 2, 3, 4)
scala> val list7 = List(5,6,7)
list7: List[Int] = List(5, 6, 7)
scala> val list8 = list1 ++ list7
list8: List[Int] = List(1, 2, 3, 5, 6, 7)
scala> val list8 = list7 ++ list1
list8: List[Int] = List(5, 6, 7, 1, 2, 3)
scala> val list9 = list1 ::: list7
list9: List[Int] = List(1, 2, 3, 5, 6, 7)
scala> val list9 = list7 ::: list1
list9: List[Int] = List(5, 6, 7, 1, 2, 3)
可变长度list
scala> import scala.collection.mutable.ListBuffer
import scala.collection.mutable.ListBuffer
scala> val list1 = ListBuffer(1,2,3)
list1: scala.collection.mutable.ListBuffer[Int] = ListBuffer(1, 2, 3)
scala> list1 += 4 //list列表追加元素
res54: list1.type = ListBuffer(1, 2, 3, 4)
scala> list1
res55: scala.collection.mutable.ListBuffer[Int] = ListBuffer(1, 2, 3, 4)
scala> list1.append(5) //list列表追加元素
res56: list1.type = ListBuffer(1, 2, 3, 4, 5)
scala> list1
res57: scala.collection.mutable.ListBuffer[Int] = ListBuffer(1, 2, 3, 4, 5)
将两个List追加到一个List里面
scala> val list2 = ListBuffer(6,7,8)
list2: scala.collection.mutable.ListBuffer[Int] = ListBuffer(6, 7, 8)
scala> list1 ++= list2 //使用 ++= 操作符可以将后面list2的内容追加到list1中
res58: list1.type = ListBuffer(1, 2, 3, 4, 5, 6, 7, 8)
scala> list1 //list1已经把list2里面的内容追加起来了
res59: scala.collection.mutable.ListBuffer[Int] = ListBuffer(1, 2, 3, 4, 5, 6, 7, 8)
scala> val list4 = ListBuffer(1,2,3)
list4: scala.collection.mutable.ListBuffer[Int] = ListBuffer(1, 2, 3)
scala> val list5 = ListBuffer(4,5,6)
list5: scala.collection.mutable.ListBuffer[Int] = ListBuffer(4, 5, 6)
scala> list4 ++ list5 //++操作符不可以将list5的内容追加到list4中,只能用 ++= 操作符才可以,如上例,这里是把两个list合并生成一个新的list的操作
res61: scala.collection.mutable.ListBuffer[Int] = ListBuffer(1, 2, 3, 4, 5, 6)
scala> list4
res62: scala.collection.mutable.ListBuffer[Int] = ListBuffer(1, 2, 3) //list4并未有list5的内容
scala> val list6 = ListBuffer(1,2,3)
list6: scala.collection.mutable.ListBuffer[Int] = ListBuffer(1, 2, 3)
scala> list6 :+ 4 //这里虽然使用了一个不可变list的操作符可以执行成功,但是依然是生成一个新的 list , list6并没有把4添加到列表中,而是生成新的一个列表
res63: scala.collection.mutable.ListBuffer[Int] = ListBuffer(1, 2, 3, 4)
scala> list6
res64: scala.collection.mutable.ListBuffer[Int] = ListBuffer(1, 2, 3)
scala> res63
res65: scala.collection.mutable.ListBuffer[Int] = ListBuffer(1, 2, 3, 4) //使用不可变列表的操作符 :+ 将列表里面元素与新元素合并且生成一上新的列表