scala yield入门详解

概念

可以遍历集合并对集合元素处理产生新集合,新集合和原有集合类型相同. (range的不同)
Array,List,Set,Range

本质

语法糖

用法

scala> val s=Array(1,2,3)
s: Array[Int] = Array(1, 2, 3)
//处理Array元素
scala> for(i <-s) yield 2*i
res15: Array[Int] = Array(2, 4, 6)

scala> val p=List(1,2,3)
p: List[Int] = List(1, 2, 3)
//处理List元素
scala> for(i <-p) yield 2*i
res16: List[Int] = List(2, 4, 6)

scala> val q=Set(1,2,3)
q: scala.collection.immutable.Set[Int] = Set(1, 2, 3)
//处理Set元素
scala> for(i <-q) yield 2*i
res17: scala.collection.immutable.Set[Int] = Set(2, 4, 6)

scala> val r=(1,2,3)
r: (Int, Int, Int) = (1,2,3)
//不支持元组
scala> for(i <-r) yield 2*i
<console>:13: error: value map is not a member of (Int, Int, Int)
       for(i <-r) yield 2*i
//处理range               ^
scala> for(i <- 1 to 10) yield 2*i
res25: scala.collection.immutable.IndexedSeq[Int] = Vector(2, 4, 6, 8, 10, 1
//可以先过滤再生成新集合
scala> for(i <-s if i%2==0) yield 2*i
res23: Array[Int] = Array(4, 8)
//可以先过滤再生成新集合
scala> for(i <-s if i>2) yield 2*i
res24: Array[Int] = Array(6, 8)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

鸭梨山大哎

你的鼓励将是我创作的最大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值