定义方式,可以new
scala> val arr = new Array[Int](3)
arr: Array[Int] = Array(0, 0, 0)
scala> arr[0] = 100
<console>:1: error: identifier expected but integer literal found.
arr[0] = 100
^
在scala中用()
scala> arr(0) = 100
scala> arr(0)
res5: Int = 100
定义方式2:
scala> val arr = Array[Int](1,2,3,4,5)
arr: Array[Int] = Array(1, 2, 3, 4, 5)
scala> arr(1) = 100;
内容可变,长度不可变
scala> arr += 8
<console>:13: error: value += is not a member of Array[Int]
arr += 8
^
scala> fx = (x: Int) => x * 10
<console>:13: error: not found: value fx
val $ires0 = fx
^
<console>:11: error: not found: value fx
fx = (x: Int) => x * 10
^
//arr经过map映射操作之后,会返回一个新的数组
scala> val fx = (x: Int) => x * 10
fx: Int => Int = <function1>
scala> arr.map(fx)
res8: Array[Int] = Array(10, 1000, 30, 40, 50)
scala> arr
res9: Array[Int] = Array(1, 100, 3, 4, 5)
//arr经过map映射操作之后,会返回一个新的数组
scala> val fx = (x: Int) => x * 10
fx: Int => Int = <function1>
scala> arr.map(fx)
res8: Array[Int] = Array(10, 1000, 30, 40, 50)
scala> arr
res9: Array[Int] = Array(1, 100, 3, 4, 5)
flatten:扁平化
scala> val arr = Array("hello you hello me","hello nimoo hello jim")
arr: Array[String] = Array(hello you hello me, hello nimoo hello jim)
scala> arr.map(_.split(" "))
res10: Array[Array[String]] = Array(Array(hello, you, hello, me), Array(hello, nimoo, hello, jim))
scala> arr.map(_.split(" ")).faltten
<console>:13: error: value faltten is not a member of Array[Array[String]]
arr.map(_.split(" ")).faltten
^
scala> arr.map(_.split(" ")).flatten
res12: Array[String] = Array(hello, you, hello, me, hello, nimoo, hello, jim)
map+ flatten
scala> arr.flatMap(_.split(" "))
res13: Array[String] = Array(hello, you, hello, me, hello, nimoo, hello, jim)
求WordCount
scala> arr
res16: Array[String] = Array(hello you hello me, hello nimoo hello jim)
scala> arr.flatMap(_.split(" ")).groupBy(x => x)
res17: scala.collection.immutable.Map[String,Array[String]] = Map(nimoo -> Array(nimoo), you -> Array(you), jim -> Array(jim), me -> Array(me), hello -> Array(hello, hello, hello, hello))
scala> arr.flatMap(_.split(" ")).groupBy(x => x).mapValues(_.length)
res18: scala.collection.immutable.Map[String,Int] = Map(nimoo -> 1, you -> 1, jim -> 1, me -> 1, hello -> 4)
scala> arr.flatMap(_.split(" ")).groupBy(x => x).mapValues(_.length).toList
res19: List[(String, Int)] = List((nimoo,1), (you,1), (jim,1), (me,1), (hello,4))
scala> arr.flatMap(_.split(" ")).groupBy(x => x).mapValues(_.length).toList.sortBy(x => x._2)
res20: List[(String, Int)] = List((nimoo,1), (you,1), (jim,1), (me,1), (hello,4))
scala> arr.flatMap(_.split(" ")).groupBy(x => x).mapValues(_.length).toList.sortBy(x => - x._2)
res21: List[(String, Int)] = List((hello,4), (nimoo,1), (you,1), (jim,1), (me,1))