Scala 中 for 循环 和 generator 的使用例子

Posted 天空之城

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Scala 中 for 循环 和 generator 的使用例子相关的知识,希望对你有一定的参考价值。

这个例子是,从每个list中,找到age最大的那个node。

class Node(vName: String, vAge: Int) {
  // Entity class
  var name: String = vName
  var age: Int = vAge
}

object TestGenerator {

  def main(args: Array[String]): Unit = {
    test()
  }

  def test(): Unit = {
    // This test case is to find out the max age node from each node‘s list

    // First, define the node 1,2,3
    val node1 = new Node("name-1", 1)
    val node2 = new Node("name-2", 2)
    val node3 = new Node("name-3", 3)

    // Second, def some List containing nodes
    val list1: List[Node] = List(node1, node2, node3)
    val list2: List[Node] = List(node1)
    val list3: List[Node] = List(node1, node2)
    val list4: List[Node] = List()
    val list5: List[Node] = Nil
    val list6: List[Node] = null


    // ==== Test Case 1 ====
    // In this test, the generator excluded the Nil and List() and null, and take the "node" out of headOption" which is Option[Node]
    // The returns are collected into node as Node

    val allList: Seq[List[Node]] = Seq(list1, list2, list3, list4, list5, list6)

    val result1 = for {
      list: List[Node] <- allList // The type List[Node] is necessary for this situation, it can help to filter out list6 (null)
      node <- list.sortWith(_.age > _.age).headOption
    } yield node

    for (r <- result1) {
      println(r.name)
    }

    println("======================================================")

    // *****************************************************************************

    // ==== Test Case 2 ====
    // In this test, use get() function to get back the list instead of Seq[List[Node]]

    def get(i: Int): List[Node] = {
      i match {
        case 1 => list1;
        case 2 => list2;
        case 3 => list3;
        case 4 => list4;
        case 5 => list5;
        case 6 => list6;
      }
    }

    // Define the array to contain the test lists
    // List 1-5 will be used for this test, but list6 (null) cannot be handled in this approach
    val arr = List(1, 2, 3, 4, 5) // list6 (null) cannot be handled thus only 1-5 here

    val result2 = for {
      i <- arr
      node <- get(i).sortWith(_.age > _.age).headOption
    } yield node

    for (r <- result2) {
      println(r.name)
    }

  }
}

 

以上是关于Scala 中 for 循环 和 generator 的使用例子的主要内容,如果未能解决你的问题,请参考以下文章

如何优化 Scala 中的 for-comprehensions 和循环?

Scala基础学习之for循环和while循环

Scala 中 for 循环 和 generator 的使用例子

scala快速入门之基础篇-循环语法

scala之for循环

2021年大数据常用语言Scala:基础语法学习 循环