package com.yl.Scala
object ListMap {
def main(args : Array[String]){
//map操作
println(List(1,2,3,4,6) map (_ + 1)) //各元素加1,生成新列表 List(2, 3, 4, 5, 7)
val data = List("Scala", "Hadoop", "Spark")
println(data map (_.length)) //生成各元素长度列表 List(5, 6, 5)
println(data map (_.toList.reverse.mkString)) //将元素逆序输出 List(alacS, poodaH, krapS)
//flatMap的操作
println(data.map(_.toList)) //List(List(S, c, a, l, a), List(H, a, d, o, o, p), List(S, p, a, r, k))
println(data.flatMap(_.toList)) //List(S, c, a, l, a, H, a, d, o, o, p, S, p, a, r, k)
println(List.range(1, 4)) //List(1, 2, 3)
println(List.range(1, 4) flatMap (i => List(1, i) map (j => (i, j))))//List((1,1), (1,1), (2,1), (2,2), (3,1), (3,3))
//List的foreach的灵活使用
var sum = 0
List(1,2,3,4,5) foreach( sum += _)
println("sum = " + sum) //sum = 15
//filter的操作
println(List(1,2,3,4,6,7,8,9,10) filter (_ % 2 == 0)) //选出偶数列表 List(2, 4, 6, 8, 10)
println(data filter (_.length == 5)) //选出长度为5的元素构成列表 List(Scala, Spark)
}
}
运行结果:
List(2, 3, 4, 5, 7)
List(5, 6, 5)
List(alacS, poodaH, krapS)
List(List(S, c, a, l, a), List(H, a, d, o, o, p), List(S, p, a, r, k))
List(S, c, a, l, a, H, a, d, o, o, p, S, p, a, r, k)
List(1, 2, 3)
List((1,1), (1,1), (2,1), (2,2), (3,1), (3,3))
sum = 15
List(2, 4, 6, 8, 10)
List(Scala, Spark)