scala使用Range来填充一个集合

Problem

    你想要使用Range来填充一个List,Array,Vector或者其他的sequence。

Solution

    对于支持range方法的集合你可以直接调用range方法,或者创建一个Range对象然后把它转化为一个目标集合。

    在第一个解决方案中,我们调用了伴生类的range方法,比如Array,List,Vector,ArrayBuffer等等:

scala> Array.range(110)
res83: Array[Int] = Array(123456789)

scala> List.range(110)
res84: List[Int] = List(123456789)

scala> Vector.range(0102)
res85: scala.collection.immutable.Vector[Int] = Vector(02468)

    对于一些集合,比如List,Array,你也可以创建一个Range对象,然后把它转化为相应的目标集合:

scala> val a = (1 to 10).toArray
a: Array[Int] = Array(12345678910)

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

scala> val l = (1 to 10).by(2).toList
l: List[Int] = List(13579)

    我们来看看那些集合可以由Range直接转化的:

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方法的集合类:

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

scala> val set = Range(05).toSet
set: scala.collection.immutable.Set[Int] = Set(01234)

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

    你也可以创建一个字符序列:

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循环:

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

    通过对Range使用map方法,你可以创建出了Int,char之外,其他元素类型的集合

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

    使用同样的方案,你可以创建二元祖集合:

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)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Soyoger

听说打赏的都进了福布斯排行榜。

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值