📜  如何在scala中反转列表

📅  最后修改于: 2022-05-13 01:55:04.549000             🧑  作者: Mango

如何在scala中反转列表

在 Scala 中,列表定义在scala.collection.immutable包下。列表是包含不可变数据的相同类型元素的集合。我们使用 reverse函数来反转 Scala 中的列表。
以下是反转列表的示例。

  • 反转一个简单的列表
    // Scala program to reverse a simple Immutable lists 
    import scala.collection.immutable._
      
    // Creating object 
    object GFG 
    { 
        // Main method 
        def main(args:Array[String]) 
        { 
            // Creating and initializing immutable lists 
            val mylist: List[String] = List("Geeks", "For",
                                    "geeks", "is", "best") 
          
            // Display the value of mylist1 
            println("Reversed List is: " + mylist.reverse) 
          
        } 
    } 
    

    输出:

    Reversed List is: List(best, is, geeks, For, Geeks)

  • 使用 for 循环反转列表
    // Scala program to print reverse immutable lists 
    // using for loop
    import scala.collection.immutable._
      
    // Creating object 
    object GFG
    { 
        // Main method 
        def main(args:Array[String]) 
        { 
            // Creating and initializing immutable lists 
            val mylist: List[String] = List("Geeks", "For", "geeks", "is",
                                            "a", "fabulous", "portal")
      
            // Display the value of mylist in
            // reverse order using for loop 
            for(element<-mylist.reverse) 
            { 
                println(element) 
            } 
        } 
    } 
    

    输出:

    portal
    fabulous
    a
    is
    geeks
    For
    Geeks

  • 使用 foreach 循环反转列表
    // Scala program to reverse a list
    // using foreach loop
    import scala.collection.immutable._
      
    // Creating object 
    object GFG
    { 
        // Main method 
        def main(args:Array[String]) 
        { 
            // Creating and initializing immutable lists 
            val mylist = List("Geeks", "For", "geeks", "is",
                            "a", "fabulous", "portal")
              
            print("Original list is: ")
              
            // Display the value of mylist using for loop 
            mylist.foreach{x:String => print(x + " ") }
              
            // calling reverse function
            println("\nReversed list: " + mylist.reverse)
        } 
    } 
    

    输出:

    Original list is: Geeks For geeks is a fabulous portal 
    Reversed list: List(portal, fabulous, a, is, geeks, For, Geeks)