[转帖]经典一例简介Scala 强大的函数式编程,丰富的集合操作方法_Android, Python及开发编程讨论区_Weblogic技术|Tuxedo技术|中间件技术|Oracle论坛|JAVA论坛|Linux/Unix技术|hadoop论坛_联动北方技术论坛  
网站首页 | 关于我们 | 服务中心 | 经验交流 | 公司荣誉 | 成功案例 | 合作伙伴 | 联系我们 |
联动北方-国内领先的云技术服务提供商
»  游客             当前位置:  论坛首页 »  自由讨论区 »  Android, Python及开发编程讨论区 »
总帖数
1
每页帖数
101/1页1
返回列表
0
发起投票  发起投票 发新帖子
查看: 3138 | 回复: 0   主题: [转帖]经典一例简介Scala 强大的函数式编程,丰富的集合操作方法        下一篇 
jie.liang
注册用户
等级:少校
经验:1003
发帖:77
精华:0
注册:2013-10-11
状态:离线
发送短消息息给jie.liang 加好友    发送短消息息给jie.liang 发消息
发表于: IP:您无权察看 2013-10-22 8:32:46 | [全部帖] [楼主帖] 楼主

情景设定:

从一组投票结果(语言,票数)中统计不同程序语言的票数并按照得票的顺序显示

原始数据

val votes = Seq(("scala", 7), ("java", 4), ("scala", 10), ("scala", 1), ("python", 10), ("python", 5))


分步操作:

1.  按语言名,把投票结果分组

val groupByLang = votes.groupBy(_._1)


此时输出 groupByLang:

Map(scala -> List((scala,7), (scala,10), (scala,1)), python -> List((python,10), (python,5)), java -> List((java,4)))


2. 统计每个分组的结果

val countVotes = groupByLang. map { case (which, counts) =>
      (which, counts.foldLeft(0)(_ + _._2))
}


 此时输出countVotes:

Map(scala -> 18, python -> 15, java -> 4)


3. 转Map为Seq,排序,反转

val finalList = countVotes.toSeq.sortBy(_._2).reverse.toList


此时输出 finalList:

List((scala,18), (python,15), (java,4))


合并在一起,简结明了:

val finalList = votes.groupBy(_._1)
.map { case (which, counts) =>
      (which, counts.foldLeft(0)(_ + _._2))
}.toSeq
.sortBy(_._2)
.reverse.toList


这里,foldLeft 也是Scala Seq提供的一个方法:

-----------------------------------------------------------------------------------------------------------
def              foldLeft[B](z: B)(op: (B, A) ⇒ B): B
Applies a binary operator to a start value and all elements of this sequence, going left to right.
Applies a binary operator to a start value and all elements of this sequence, going left to right.
Note: will not terminate for infinite-sized collections.
B
the result type of the binary operator.
z
the start value.
op
the binary operator.
returns
the result of inserting op between consecutive elements of this sequence,          going left to right with the start value z on the left:

op(...op(z, x_1), x_2, ..., x_n)

where x1, ..., xn are the elements of this sequence.
----------------------------------------------------------------------------------------------------------------------------


举个例子:

设 testList((scala,7), (scala,10), (scala,1))

teestList.foldLeft(0)(_ + _._2))   的结果 是  18.

Scala的 集合, Seq,Set,Map都提供了许多有用的方法, 而且可以链式调用。

具体视需求查Scala 的Api:

http://www.scala-lang.org/api/2.10.3/#package




赞(0)    操作        顶端 
总帖数
1
每页帖数
101/1页1
返回列表
发新帖子
请输入验证码: 点击刷新验证码
您需要登录后才可以回帖 登录 | 注册
技术讨论