zoukankan      html  css  js  c++  java
  • How do I iterate over a Scala List (or more generally, a sequence) using theforeach method or for loop?

    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.

  • 相关阅读:
    JAVA获取指定天数之后的日期
    JAVA携带参数(带有参数)直接发送POST请求
    JAVA使用itext根据模板生成PDF文档
    office2007(word2007)另存为pdf文档
    JAVA判断某个元素是否在某个数组中
    SpringBoot单元测试demo
    tomcat启动报错There is insufficient memory for the Java Runtime Environment to continue
    JAVA中价格金额的存储类型
    JAVA获取当前日期的下周一到下周日的所有日期集合
    Golang package和目录的区别
  • 原文地址:https://www.cnblogs.com/seaspring/p/5645198.html
Copyright © 2011-2022 走看看