Scala中for循环的yield用法

**

概念

**
for循环中的yield会将for循环中的值保存下来,保存到一个集合中,在循环结束的时候会将集合全部输出,如果被循环的是map,则输出的就是map。如果被循环的是list,则输出的就是list,以此类推。

使用println进行输出

scala> for (i <- 1 to 5)
     | println (i)
1
2
3
4
5

使用yield输出

scala> for (i <- 1 to 5)
     | yield i
res3: scala.collection.immutable.IndexedSeq[Int] = Vector(1, 2, 3, 4, 5)
scala> val a = for (i <- 1 to 5)
     | yield i
a: scala.collection.immutable.IndexedSeq[Int] = Vector(1, 2, 3, 4, 5)

scala> a
res4: scala.collection.immutable.IndexedSeq[Int] = Vector(1, 2, 3, 4, 5)

 

循环过滤if判断,并返回值

scala> for (e <- a if e % 2 == 0 )
     | yield e
res5: scala.collection.immutable.IndexedSeq[Int] = Vector(2, 4)
scala> a
res6: scala.collection.immutable.IndexedSeq[Int] = Vector(1, 2, 3, 4, 5)

scala> val b = 6 to 7
b: scala.collection.immutable.Range.Inclusive = Range(6, 7)

scala> for {
     | x <- a
     | y <- b
     | }
     | yield (x,y)
res7: scala.collection.immutable.IndexedSeq[(Int, Int)] = Vector((1,6), (1,7), (2,6), (2,7), (3,6), (3,7), (4,6), (4,7), (5,6), (5,7))

scala> for {
     | y <- b
     | x <- a
     | }
     | yield (x,y)
res8: scala.collection.immutable.IndexedSeq[(Int, Int)] = Vector((1,6), (2,6), (3,6), (4,6), (5,6), (1,7), (2,7), (3,7), (4,7), (5,7))

 

yield复杂点的使用

//找出以固定字符串结尾的文件
scala> def getTextFile(path:String) : Array[java.io.File] =
     | for {
     | file <- new java.io.File(path).listFiles
     | if file.isFile
     | if file.getName.endsWith(".txt")
     | }
     | yield file
getTextFile: (path: String)Array[java.io.File]

scala> getTextFile(".")
res9: Array[java.io.File] = Array(./a.txt)

 

实际开发中的应用

object Loop {
  def main(args: Array[String]): Unit = {
    val str = Array(1,2,3,4,5,6,7)

    for(i <- str ) {
      println(i)
    }

    val add  = for (i <- str) yield i +100
    println (add.toBuffer)

  }
}

 

这是输出结果

1
2
3
4
5
6
7
ArrayBuffer(101, 102, 103, 104, 105, 106, 107)

Process finished with exit code 0

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值