第十章 Scala 容器基礎(二十五):使用Range來填充一個集合

Problem

    你想要使用Range來填充一個List,Array,Vector或者其餘的sequence。
spa

Solution

    對於支持range方法的集合你能夠直接調用range方法,或者建立一個Range對象而後把它轉化爲一個目標集合。scala

    在第一個解決方案中,咱們調用了伴生類的range方法,好比Array,List,Vector,ArrayBuffer等等:code

scala> Array.range(1, 10)
res83: Array[Int] = Array(1, 2, 3, 4, 5, 6, 7, 8, 9)

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

scala> Vector.range(0, 10, 2)
res85: scala.collection.immutable.Vector[Int] = Vector(0, 2, 4, 6, 8)

    對於一些集合,好比List,Array,你也能夠建立一個Range對象,而後把它轉化爲相應的目標集合:對象

scala> val a = (1 to 10).toArray
a: Array[Int] = Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

scala> val l = (1 to 10) by 2 toList
warning: there were 1 feature warning(s); re-run with -feature for details
l: List[Int] = List(1, 3, 5, 7, 9)

scala> val l = (1 to 10).by(2).toList
l: List[Int] = List(1, 3, 5, 7, 9)

    咱們來看看那些集合能夠由Range直接轉化的:it

def toArray: Array[A]
def toBuffer[A1 >: Int]: Buffer[A1]
def toIndexedSeq: IndexedSeq[Int]
def toIterator: Iterator[Int]
def toList: scala.List[Int]
def toMap[T, U]: collection.Map[T, U]
def toParArray: ParArray[Int]
def toSet[B >: Int]: Set[B]
def toStream: Stream[Int]
def toTraversable: collection.Traversable[Int]
def toVector: scala.Vector[Int]

    使用這種方案咱們能夠把Range轉爲Set等,不支持range方法的集合類:io

scala> val set = Set.range(0, 5)
<console>:8: error: value range is not a member of object scala.collection.immutable.Set
       val set = Set.range(0, 5)
                     ^

scala> val set = Range(0, 5).toSet
set: scala.collection.immutable.Set[Int] = Set(0, 1, 2, 3, 4)

scala> val set = (0 to 10 by 2).toSet
set: scala.collection.immutable.Set[Int] = Set(0, 10, 6, 2, 8, 4)

    你也能夠建立一個字符序列:console

scala> val letters = ('a' to 'f').toList
letters: List[Char] = List(a, b, c, d, e, f)

scala> val letters = ('a' to 'f' by 2).toList
letters: List[Char] = List(a, c, e)

    Range還能用於for循環:for循環

scala> for(i <- 0 until 10 by 2) println(i)
0
2
4
6
8

Discussion

    經過對Range使用map方法,你能夠建立出了Int,char以外,其餘元素類型的集合
table

scala> val l = (1 to 3).map(_ * 2.0).toList
l: List[Double] = List(2.0, 4.0, 6.0)

    使用一樣的方案,你能夠建立二元祖集合:class

scala> val t = (1 to 5).map(e => (e, e*2))
t: scala.collection.immutable.IndexedSeq[(Int, Int)] = Vector((1,2), (2,4), (3,6), (4,8), (5,10))

    二元祖集合很容易轉換爲Map:

scala> val map = t.toMap
map: scala.collection.immutable.Map[Int,Int] = Map(5 -> 10, 1 -> 2, 2 -> 4, 3 -> 6, 4 -> 8)
相關文章
相關標籤/搜索