val a = Array(2, 4, 5, 6)
val result = for(elem <- a) yield 2 * elem //result = (4,8, 10, 12)
val result1 = for(elem <- a if elem % 2 == 0) yield 2 * elem //result1 = (4,8,12)
val result2 = a.filter(_ % 2 == 0).map(2 * _ ) //result = (4,8,12)
val result3 = a.filter(_ % 2 == 0) map {2 * _ } //result = (4, 8, 12)
举例:删除一个数组内除了第一个负数外的其他负数
def removeNeg(a: Array[Int]) = { var first = true val indexes = for(i <- 0 until a.length if first || a(i) > 0) yield { if(a(i) < 0) first = false;i } for(j <- 0 until indexes.length) a(j) = a(indexes(j)) val b = a.toBuffer b.trimEnd(a.length - indexes.length) b.toArray }
求和
Array/ArrayBuffer(...).sum
最大最小
Array/ArrayBuffer(...).max/min
排序
不修改原始版本
val b = Array/ArrayBuffer(...)
val bSorted = b.sorted
val bDescending = b.sortedWith(_>_)
在原有数组基础上排序(不能对数组缓冲操作)
val a = Array()
scala.util.Sorting.quichSort(a)
显示数组或数组缓冲的内容
a.mkString(" and ") //"1 and 2 and 3"
a.mkString("<", ",", ">") //"<1,2,3>"