Scala 流 和 视图

流(Stream)它包含的元素是延迟计算的。它不会立即计算,而是在需要计算的时候才真正计算

你可以对其他集合应用 视图(View)方法来得到类似的结果,视图(View)方法交出的是一个其方法总是被懒执行的集合。

跟流不同,视图并不会缓存任何值

跟流一样,用 force方法可以对懒视图强制求值

 

package main

object Test {

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

    val list = List(1 to 1000000: _*);
    println(list.getClass.getName); //scala.collection.immutable.$colon$colon

    val time1 = System.currentTimeMillis();
    val where1 = list
      .filter(x => x % 10 == 0 && x % 5 == 0 && x % 3 == 0)
      .sortWith(_ > _);

    println("filter");
    println(where1.getClass.getName); //scala.collection.immutable.$colon$colon
    println("条数=" + where1.size);
    println("耗时=" + (System.currentTimeMillis() - time1));
    println("head=" + where1.head);

    System.gc();

    val time2 = System.currentTimeMillis();
    val where2 = list.toStream
      .filter(x => x % 10 == 0)
      .filter(x => x % 5 == 0)
      .filter(x => x % 3 == 0)
      .sortWith(_ > _)
      .force;

    println();
    println("stream filter");
    println(where2.getClass.getName); //scala.collection.immutable.Stream$Cons
    println("条数=" + where2.size);
    println("耗时=" + (System.currentTimeMillis() - time2));
    println("head=" + where2.head);

    System.gc();

    val time3 = System.currentTimeMillis();
    val view = list.view
      .filter(x => x % 10 == 0)
      .filter(x => x % 5 == 0)
      .filter(x => x % 3 == 0)
      .sortWith(_ > _)
      .force;

    println()
    println("view filter");
    println(view.getClass.getName); //scala.collection.immutable.$colon$colon
    println("条数=" + view.size);
    println("耗时=" + (System.currentTimeMillis() - time3));

    println("head=" + view.head);
  }
}

 

posted @ 2019-07-26 22:59  茗::流  阅读(156)  评论(0)    收藏  举报
如有雷同,纯属参考。如有侵犯你的版权,请联系我。