Scala for循环过滤

Scala for循环过滤教程

Scala 中,for 循环 可以使用一个或多个 if 语句 来过滤一些元素。

Scala for循环过滤详解

语法

for( var x <- List if condition1; if condition2... ){ statement(s); }

参数

参数 描述
for for 循环使用的关键字。
x 循环变量。
List 要遍历的集合。
condition1 过滤条件。
condition2 过滤条件。
statements 每次循环执行的代码逻辑。

说明

你可以使用分号(;)来为表达式添加一个或多个的过滤条件。

案例

for循环过滤

使用 for 循环,遍历过滤

object HaiCoder { def main(args: Array[String]) : Unit = { println("嗨客网(www.haicoder.net)!\n") var a = 0; val numList = List(1,2,3,4,5,6,7,8,9,10); // for 循环 for( a <- numList if a != 3; if a < 8 ){ println( "Value of a: " + a ); } } }

程序运行后,控制台输出如下:

16_Scala for循环过滤.png

我们在 for 循环里面使用 if 语句可以过滤条件。

Scala for循环过滤总结

在 Scala 中,for 循环可以使用一个或多个 if 语句来过滤一些元素。语法为:

for( var x <- List if condition1; if condition2... ){ statement(s); }