美文网首页
scala(十五) List

scala(十五) List

作者: 万事万物 | 来源:发表于2021-07-02 07:31 被阅读0次

不可变List

不可变List的创建:

  1. 通过apply方法创建: List[元素类型](初始元素,...)
val list=List[Int](1,2,3,4,5,6,7,8,9,10)
  1. 通过 :: 方法创建: 初始元素 :: 初始元素 :: ... :: Nil/不可变List
val list=1::2::3::4::5::6::7::8::9::10::Nil

Nil相当于一个空的List,Nil与不可变List的关系类似Null与String的关系,使用Nil给不可变List赋予初始值的时候必须定义变量类型
:: 最右边必须是Nil或者是不可变List
:: 是添加单个元素
::: 是添加一个集合所有元素

查看支持的api

scala> val list1=List[Int](1,2,3,4,5,6,7,8,9,10)
list1: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

scala> list1.
++              flatMap              min                 sortBy
++:             flatten              minBy               sortWith
+:              fold                 mkString            sorted
/:              foldLeft             nonEmpty            span
:+              foldRight            orElse              splitAt
::              forall               padTo               startsWith
:::             foreach              par                 stringPrefix
:\              genericBuilder       partition           sum
WithFilter      groupBy              patch               tail
addString       grouped              permutations        tails
aggregate       hasDefiniteSize      prefixLength        take
andThen         hashCode             product             takeRight
apply           head                 productArity        takeWhile
applyOrElse     headOption           productElement      to
canEqual        indexOf              productIterator     toArray
collect         indexOfSlice         productPrefix       toBuffer
collectFirst    indexWhere           reduce              toIndexedSeq
combinations    indices              reduceLeft          toIterable
companion       init                 reduceLeftOption    toIterator
compose         inits                reduceOption        toList
contains        intersect            reduceRight         toMap
containsSlice   isDefinedAt          reduceRightOption   toSeq
copyToArray     isEmpty              repr                toSet
copyToBuffer    isTraversableAgain   reverse             toStream
corresponds     iterator             reverseIterator     toString
count           last                 reverseMap          toTraversable
diff            lastIndexOf          reverse_:::         toVector
distinct        lastIndexOfSlice     runWith             transpose
drop            lastIndexWhere       sameElements        union
dropRight       lastOption           scan                unzip
dropWhile       length               scanLeft            unzip3
endsWith        lengthCompare        scanRight           updated
equals          lift                 segmentLength       view
exists          map                  seq                 withFilter
filter          mapConserve          size                zip
filterNot       max                  slice               zipAll
find            maxBy                sliding             zipWithIndex
  • 初始化数据
val list1=List[Int](1,2,3,4,5)
val list2=6::7::8::9::10::Nil
  • 添加数据

++将一组元素添加到集合末尾,并返回一个新的集合。

val arr=list1.++(list2)
println(arr)
List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

++:将一组元素添加到集合头部,并返回一个新的集合。

val arr=list1.++:(list2)
println(arr)
List(6, 7, 8, 9, 10, 1, 2, 3, 4, 5)

:::将一组元素添加到集合头部,并返回一个新的集合。

val arr=list1.:::(list2)
println(arr)
List(6, 7, 8, 9, 10, 1, 2, 3, 4, 5)

+:将单个元素添加到集合头部,并返回一个新的集合。

val arr=list1.+:(100)
println(arr)
List(100, 1, 2, 3, 4, 5)

::将单个元素添加到集合头部,并返回一个新的集合。

val arr=list1.::(100)
println(arr)
List(100, 1, 2, 3, 4, 5)

:+将单个元素添加到集合尾部,并返回一个新的集合。

val arr=list1.:+(100)
println(arr)
List(1, 2, 3, 4, 5, 100)
  • 删除元素

drop(count):从左到右,弹出count 个元素,返回一个新的数组

val list=List[Int](23,44,23,56,5)
val newList: List[Int] = list.drop(1)
println(newList)
List(44, 23, 56, 5)

弹出2个元素

val newList: List[Int] = list.drop(2)
println(newList)
List(23, 56, 5)
  • 修改元素

使用updated 函数,对索引位置元素赋值

val list=List[Int](23,44,23,56,5)

val newList=list.updated(0,100)
println(newList)
List(100, 44, 23, 56, 5)
  • 遍历元素
val list=List[Int](23,44,23,56,5)
    
for(e <-list){
  println(s"e=$e")
}
e=23
e=44
e=23
e=56
e=5
  • 获取元素长度
val list=List[Int](23,44,23,56,5)
println(s"length=${list.length}") // 5
println(s"size=${list.size}") // 5
  • 不可变转可变(toBuffer)
val list=List[Int](23,44,23,56,5)
val bufferList: mutable.Buffer[Int] = list.toBuffer

可变List

创建可变List

  1. 通过apply方法: ListBuffer[元素类型](初始元素,...)
val list=ListBuffer[Int](1,2,3,4,5)

查看ListBuffer支持哪些api
需要导包

scala> import scala.collection.mutable.ListBuffer
import scala.collection.mutable.ListBuffer
scala> val list=ListBuffer[Int](1,2,3,4,5)
list: scala.collection.mutable.ListBuffer[Int] = ListBuffer(1, 2, 3, 4, 5)

scala> list.
++              endsWith             mapResult           sortBy
++:             equals               max                 sortWith
++=             exists               maxBy               sorted
++=:            filter               min                 span
+:              filterNot            minBy               splitAt
+=              find                 mkString            startsWith
+=:             flatMap              nonEmpty            stringPrefix
-               flatten              orElse              sum
--              fold                 padTo               tail
--=             foldLeft             par                 tails
-=              foldRight            partition           take
/:              forall               patch               takeRight
:+              foreach              permutations        takeWhile
:\              genericBuilder       prefixLength        to
<<              groupBy              prepend             toArray
WithFilter      grouped              prependAll          toBuffer
addString       hasDefiniteSize      prependToList       toIndexedSeq
aggregate       hashCode             product             toIterable
andThen         head                 reduce              toIterator
append          headOption           reduceLeft          toList
appendAll       indexOf              reduceLeftOption    toMap
apply           indexOfSlice         reduceOption        toSeq
applyOrElse     indexWhere           reduceRight         toSet
canEqual        indices              reduceRightOption   toStream
clear           init                 remove              toString
clone           inits                repr                toTraversable
collect         insert               result              toVector
collectFirst    insertAll            reverse             transform
combinations    intersect            reverseIterator     transpose
companion       isDefinedAt          reverseMap          trimEnd
compose         isEmpty              runWith             trimStart
contains        isTraversableAgain   sameElements        union
containsSlice   iterator             scan                unzip
copyToArray     last                 scanLeft            unzip3
copyToBuffer    lastIndexOf          scanRight           update
corresponds     lastIndexOfSlice     segmentLength       updated
count           lastIndexWhere       seq                 view
diff            lastOption           size                withFilter
distinct        length               sizeHint            zip
drop            lengthCompare        sizeHintBounded     zipAll
dropRight       lift                 slice               zipWithIndex
dropWhile       map                  sliding
  • 添加数据

初始化数据

val list1=ListBuffer[Int](1,2,3,4,5)
val list2=ListBuffer[Int](6,7,8,9,10)

++添加一组元素到集合尾部,并返回一个新的集合

val newList: ListBuffer[Int] = list1.++(list2)
println(newList)
ListBuffer(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

++:添加一组元素到集合头部,并返回一个新的集合

val newList: ListBuffer[Int] = list1.++:(list2)
println(newList)
ListBuffer(6, 7, 8, 9, 10, 1, 2, 3, 4, 5)

++=添加一组元素到元素集合的尾部(不返回新的集合)

list1.++=(list2)
println(list1)
ListBuffer(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

++=:添加一组元素到元素集合的头部(不返回新的集合)

list1.++=:(list2)
println(list1)
ListBuffer(6, 7, 8, 9, 10, 1, 2, 3, 4, 5)

+: 添加单个元素到集合的头部,并返回新的集合

val newList: ListBuffer[Int] = list1.+:(100)
println(newList)
ListBuffer(100, 1, 2, 3, 4, 5)

:+ 添加单个元素到集合的未部,并返回新的集合

val newList: ListBuffer[Int] = list1.:+(100)
println(newList)
ListBuffer(1, 2, 3, 4, 5, 100)

+=添加单个元素到集合的尾部(不返回新的集合)

list1.+=(100)
println(list1)
ListBuffer(1, 2, 3, 4, 5, 100)

+=:添加单个元素到集合的头部(不返回新的集合)

 list1.+=:(100)
println(list1)
ListBuffer(100, 1, 2, 3, 4, 5)
  • 删除数据

-删除集合中单个元素,并返回一个新的集合

val newList: ListBuffer[Int] = list1.-(2)
println(newList)
ListBuffer(1, 3, 4, 5)

--删除集合中一组元素,并返回一个新的集合

val newList: ListBuffer[Int] = list1.--(ListBuffer[Int](2,4,3))
println(newList)
ListBuffer(1, 5)

--=在原始集合中删除一组元素(不返回一个新的集合)

list1.--=(ListBuffer[Int](2,4,3))
println(list1)
ListBuffer(1, 5)

-=在原始集合中删除单个元素(不返回一个新的集合)

list1.-=(3)
println(list1)
ListBuffer(1, 2, 4, 5)
  • 修改原始

update(索引,值)根据索引修改,不返回新的集合

val list=ListBuffer[Int](1,2,3,4,5)
list.update(2,100)
println(list)
ListBuffer(1, 2, 100, 4, 5)

updated(索引,值)根据索引修改,返回新的集合

val newList=list.updated(2,100)
println(newList)
ListBuffer(1, 2, 100, 4, 5)
  • 遍历原始
val list=ListBuffer[Int](1,2,3,4,5)
for(e <- list){
  println(s"e=$e")
}
e=1
e=2
e=3
e=4
e=5
  • 获取原始长度
println(list.length)
println(list.size)
  • 可变集合转不可变集合
val list=ListBuffer[Int](1,2,3,4,5)
val newList: List[Int] = list.toList

相关文章

网友评论

      本文标题:scala(十五) List

      本文链接:https://www.haomeiwen.com/subject/bnsgyltx.html