Scala List/sequence FAQ: How do I iterate over a Scala List (or more generally, a sequence) using theforeach method or for loop?

There are a number of ways to iterate over a Scala List using theforeach method (which is available to Scala sequences like ListArray,ArrayBufferVectorSeq, etc.) andfor comprehension, and I'll show a few of those approaches here.

1) Iterating lists with foreach

A common way to iterate over a Scala List is with the foreach method. Here's a quote about foreach from the book Programming in Scala:

foreach takes a procedure -- a function with a result type Unit -- as the right operand. It simply applies the procedure to each List element. The result of the operation is again Unit; no list of results is assembled.

Here's a simple example showing how to use foreach to print every item in a List:

scala> val x = List(1,2,3)
x: List[Int] = List(1, 2, 3) scala> x.foreach { println }
1
2
3

If you've used a programming language like Ruby, this syntax will look familiar to you.

Note that this is a relatively common way to use theforeach method. Because foreach takes a procedure that doesn’t return anything, and because the result offoreach is also Unit, the foreach method is typically used for its side effects -- something like this example where output is printed for a user to see.

This next example shows a way to sum all the elements in a list usingforeach:

scala> var sum = 0
sum: Int = 0 scala> val x = List(1,2,3)
x: List[Int] = List(1, 2, 3) scala> x.foreach(sum += _) scala> println(sum)
6

Note that this second example is not a common or preferred way to useforeach; I’m just trying to show some different possibilities. (When I first wrote this example it wasn’t the worst thing in the world to use a var field, but with more and more developers preferrring functional programming, the use of var fields is discouraged.)

2) Scala Lists and the for comprehension

The Scala for comprehension is not specific to lists, but is an extremely powerful way to operate on a List and other sequences. Here's a simple example of how to iterate over a sequence using the for comprehension (also known as a “for loop”):

scala> val names = Vector("Bob", "Fred", "Joe", "Julia", "Kim")
names: Vector[java.lang.String] = Vector(Bob, Fred, Joe, Julia, Kim) scala> for (name <- names) println(name)
Bob
Fred
Joe
Julia
Kim

So far, so good. Now let's add a simple if clause to the for comprehension to print only the elements we want to print:

scala> val names = Vector("Bob", "Fred", "Joe", "Julia", "Kim")
names: Vector[java.lang.String] = Vector(Bob, Fred, Joe, Julia, Kim) scala> for (name <- names if name.startsWith("J"))
| println(name)
Joe
Julia

If you already know about the for comprehension, you know that you can add multiple if clauses, and much more functionality. I could easily write an entire tutorial on the Scala for comprehension, so to keep this tutorial short, I'll stop here for now.

Before leaving, I will add these notes however, from the book Programming in Scala:

Scala provides the for comprehension, which provides syntactically pleasing nesting of map,flatMap, and filter ... The for comprehension is nota looping construct, but is a syntactic construct the compiler reduces to mapflatMap, and filter.

3) More detailed examples

I apologize that these examples are not as detailed as I prefer. If I had more free time I’d expand on them here, but sadly I don’t have that free time right now. So I’ll just have to say, “Please see the Scala Cookbook, where I cover the for loop and foreach method in great detail”:

4) Summary: Iterating Scala lists with foreach and for

I hope this short tutorial on how to iterate over a Scala List (and other sequences) using the foreach method and for comprehension have been helpful. As you can tell from these examples, there's much more power available to you with both approaches, which is one of the great things about the Scala programming language.

How do I iterate over a Scala List (or more generally, a sequence) using theforeach method or for loop?的更多相关文章

  1. Beginning Scala study note(3) Object Orientation in Scala

    1. The three principles of OOP are encapsulation(封装性), inheritance(继承性) and polymorphism(多态性). examp ...

  2. Scala access modifiers and qualifiers in detail

    来自:http://www.jesperdj.com/2016/01/08/scala-access-modifiers-and-qualifiers-in-detail/ Just like Jav ...

  3. Scala 具体的并行集合库【翻译】

    原文地址 本文内容 并行数组(Parallel Array) 并行向量(Parallel Vector) 并行范围(Parallel Range) 并行哈希表(Parallel Hash Tables ...

  4. Scala并发编程react、loop代码实战具体解释

    演示样例代码及凝视: //scala并发编程中的react和loop,共同特点: //通过线程存用的方式让性能有所提升. //Actor本身的运行,被actor子系统管理的时候,会有一个或者多个远程的 ...

  5. Scala中的Implicit详解

    Scala中的implicit关键字对于我们初学者像是一个谜一样的存在,一边惊讶于代码的简洁, 一边像在迷宫里打转一样地去找隐式的代码,因此我们团队结合目前的开发工作,将implicit作为一个专题进 ...

  6. Scala代码开发 metaTable(元表)

    使用Scala语言开发时,自动生成get和set方法 不用写return进行返回, 因为它的最后一行就是返回值 先建立四个层(层层递进) domain 表结构的建立 repository(DAO) 实 ...

  7. [原创]Scala学习:编写Scala脚本

    scala支持脚本 1)在/opt/scala-script下创建一个文件hello.scala 编辑内容如下: $ hello ,this is the first scala script 2)运 ...

  8. learning scala How To Create Variable Argument Function - varargs :_ *

    Scala collection such as List or Sequence or even an Array to variable argument function using the s ...

  9. 【Scala】什么是隐式转换?它又能用来干嘛?该怎么用

    文章目录 定义 隐式参数 隐式转换 隐式值:给方法提供参数 隐式视图 将Int和Double类型转换为String 狗狗学技能(使用别的类中的方法) 使用规则 定义 隐式参数 隐式参数指在函数或者方法 ...

随机推荐

  1. Linux Bash 脚本:自己定义延迟代码块(裸数据保存方案)

    结合 alias 和 read 使用方法.能够保存一些将要延迟执行的脚本,或者裸数据(字符串不被扩展)到一个变量中.以备后用. $ alias BEGIN='read -d "" ...

  2. UEFI是什么?与BIOS的区别在哪里?UEFI详解!

    前几天在帮同事小何笔记本电脑安装64位 Windows 7 的时候,遇到一个从来没有碰到过的问题,使用光盘安装时,提示:Windows无法安装到这个磁盘.选中的磁盘具有MBR分区表.在EFI系统上,W ...

  3. SIT与UAT的分别

    在企业级软件的测试过程中,经常会划分为三个阶段——单元测试,SIT和UAT,如果开发人员足够,通常还会在SIT之前引入代码审查机制(Code Review)来保证软件符合客户需求且流程正确.下面简单介 ...

  4. RESTFul中的那些事(2)----怎样支持RESTFul的HTTP Patch方法?

    我们在调用RESTFul服务的时候,有的时候.第三方的服务会提供支持PATCH 操作的方法,在这样的情况下.我们假设我们以下的这样的方式, 去调用PATCH操作.肯定会返回40X的错误. PATCH ...

  5. 19、Java访问修饰符

    修饰符 本类 同一个包中的类 子类 其它类 public 可以访问 可以访问 可以访问 可以访问 protected 可以访问 可以访问 可以访问 不能访问 默认 可以访问 可以访问 不能访问 不能访 ...

  6. 使用SpringMVC搭建第一个项目

    概述 使用SpringMVC搭建第一个项目,入门教程,分享给大家. 详细 代码下载:http://www.demodashi.com/demo/10596.html 一.概述 1.什么是Spring ...

  7. 6款国内、国外开源PHP轻论坛CMS程序

    随着移动互联网对于传统互联网的冲击,用户群更加注重信息的及时性和有效性的简便分享和获取,传统的社区模式经过多年的积累沉淀很深,尤其对于新兴的社区用户群和站长来说,如果需要挑战目前已经非常成熟的社区群还 ...

  8. TaskController.java 20160712

    package main.java.com.zte.controller.system; import java.io.PrintWriter; import java.util.ArrayList; ...

  9. Vijos1935不可思议的清晨题解

    - 题目来源 https://vijos.org/p/1935 描写叙述 今天,是2015年2月14日,星期六,情人节. 这真是一个不可思议的日子.今天早上.我打开窗户,太阳居然从西側升了起来. 我与 ...

  10. C-从源文件到可执行文件的详细编译链接过程

    一直用windows一键搞定, 没有去了解详细的编译链接过程, 今天看了一篇文章, 顺便实验和记录在Linux下逐步生成的步骤. 预处理: 执行#include, #define, #if, #ifd ...