for(...)yield循环创建了一个类型与原始集合相同的新集合。
val a1 = Array(2, 3, 5, 7, 11) val result = for (elem <- a1) yield 2 * elem for (elem <- result) { println(elem) }
结果
4 6 10 14 22
通过守卫:for中的if 来实现处理那些满足特定条件的元素。
val a1 = Array(2, 3, 5, 7, 11) val result = for (elem <- a1 if elem % 2 == 0) yield 2 * elem for (elem <- result) { println(elem) }
结果:
4
另一种方法是用filter
val a1 = Array(2, 3, 5, 7, 11) val result = a1.filter(_ % 2 == 0).map(2 * _) for (elem <- result) { println(elem) }
结果
4
另一种形式
val a1 = Array(2, 3, 5, 7, 11) val result = a1.filter(_ % 2 == 0) map { 2 * _ } for (elem <- result) { println(elem) }
结果
4
给定一个整数的数组,想移除除第一个负数之外的所有负数。
import scala.collection.mutable.ArrayBuffer
val a1 = ArrayBuffer(2, 3, 5, 7, 11) var first = true var n = a1.length var i = 0 while (i < n) { if (a1(i) >= 0) i += 1 else { if (first) { first = false; i += 1 } else { a1.remove(i); n -= 1 } } }
这个方案其实并不那么好:从数组中移除元素并不高效,把非负数值拷贝到前端好得多。
首先收集需要保留的下标
val a1 = ArrayBuffer(1, -2, 3, -4,5, 6, -7, 8, -9, 10) var first = true val indexes = for (i <- 0 until a1.length if first || a1(i) >= 0) yield { if (a1(i) < 0) first = false; i } for(elem <- indexes ){ print(elem+",") } println()
结果
0,1,2,4,5,7,9,
然后将元素移动到该去的位置,并截断尾端
for (j <- 0 until indexes.length) { a1(j) = a1(indexes(j)) } println("截断前:") for (elem <- a1) { print(elem+",") } println()
结果
截断前: 1,-2,3,5,6,8,10,8,-9,10,
截断
println("截断后") a1.trimEnd(a1.length - indexes.length) for (elem <- a1) { print(elem + ",") }
结果
1,-2,3,5,6,8,10,
时间: 2024-10-17 10:08:41