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)
        }
    
      }
    }
  • 相关阅读:
    关于属性值
    REG小探
    纯CSS实现立方体旋转
    css3总结(三)立方体、动画、web字体、字体图标、弹性布局、多列布局、伸缩盒子
    css3总结(二)背景色渐变、background、边框图片、过渡、2d变换、3d变换
    css3总结(一)属性选择器、伪类、伪元素、盒模型、边框圆角、文本阴影、边框阴影
    自定义视频播放器(功能包括:播放/暂停,全屏,跳播)
    html5总结
    Git workflow- Git 工作流
    nodejs使用redis实现sub/pub
  • 原文地址:https://www.cnblogs.com/pekkle/p/9149957.html
Copyright © 2011-2022 走看看