zoukankan      html  css  js  c++  java
  • 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)
        }
    
      }
    }
  • 相关阅读:
    1.3计算机网络体系结构及OSI七层参考模型与TCP/IP参考模型
    1.2计算机网络性能指标
    1.1数据交换——电路、报文、分组交换
    一、计算机网络概述
    计算机网络随笔序言及索引
    CCF-CSP历年试题详解(不断更新中)
    【python】序列
    算法课-母函数专题
    算法课-大数专题
    算法课-暴力搜索
  • 原文地址:https://www.cnblogs.com/pekkle/p/9149957.html
Copyright © 2011-2022 走看看