scala入门初级代码训练-33List的map,flatmap,filter

原创文章,转载请注明出处!

原文地址: http://www.ptbird.cn/2016/07/19/scala-chuji-demo-33/

There I am,in the world more exciting!

by postbird

www.ptbird.cn



package com.ptbird.scala

/**
* Created by postbird on 2016/5/26.
*/
object ListTest4 {
def main(args: Array[String]): Unit = {
println(List(1, 2, 3, 4, 6) map (_ + 1))
//List(2, 3, 4, 5, 7)
val data = List("scala", "spark", "hadoop")
println(data map (_.length))
//List(5, 5, 6)
println(data map (_.toList.reverse.mkString))
//List(alacs, kraps, poodah)
println(data.map(_.toList))
//List(List(s, c, a, l, a), List(s, p, a, r, k), List(h, a, d, o, o, p))
println(data.flatMap(_.toList))
//List(s, c, a, l, a, s, p, a, r, k, h, a, d, o, o, p)
println(List.range(1, 10) flatMap (i => List.range(1, i) map (j => (i, j))))
//List((2,1), (3,1), (3,2), (4,1), (4,2), (4,3), (5,1), (5,2), (5,3), (5,4), (6,1), (6,2), (6,3), (6,4), (6,5), (7,1), (7,2), (7,3), (7,4), (7,5), (7,6), (8,1), (8,2), (8,3), (8,4), (8,5), (8,6), (8,7), (9,1), (9,2), (9,3), (9,4), (9,5), (9,6), (9,7), (9,8))

var sum = 0;
List(1, 2, 3, 4, 5) foreach (sum += _)
println("Sum: " + sum)
println(List(1, 2, 3, 4, 5, 6, 6, 7, 8) filter (x => x % 2 == 0))
println(data filter (_.length == 5))
// Sum: 15
// List(2, 4, 6, 6, 8)
// List(scala, spark)
}
}

欢迎评论。
lingkb » scala入门初级代码训练-33List的map,flatmap,filter

发表评论