简体   繁体   English

Scala Stream与Java Stream Laziness的区别

[英]Scala Stream vs Java Stream Laziness Difference

I'm new to the concept of lazy evaluation. 我是懒惰评估概念的新手。 When I execute this line of code in Scala; 当我在Scala中执行这行代码时;

"12334".grouped(1).toStream.filter{n => println("n:" +n ); n=="3";}

It prints out: 打印出来:

n:1
n:2
n:3

But when I run something similar in Java, like: 但是当我在Java中运行类似的东西时,例如:

List<String> myList = new ArrayList<>(Arrays.asList("12334".split("")));

Stream<String> myList2 = myList.stream().filter(a -> {System.out.println("a:" +a);return "3".equals(a);});

It terminates silently without writing anything to console line. 它无声地终止,无需向控制台行写任何内容。 Java's behavior seems more reasonable to me because Streams are lazily evaluated and I did not collect or try to print result. Java的行为对我来说似乎更合理,因为Streams被懒惰地评估,我没有收集或尝试打印结果。 But in Scala even if I did not consume stream it prints out some information. 但是在Scala中,即使我没有消耗流,它也会输出一些信息。 So my question is what is causing that difference? 所以我的问题是导致这种差异的原因是什么?

It's due to the fact that filter isn't entirely lazy. 这是因为filter并不完全是懒惰的。 It has this piece of code: 它有这段代码:

while (!rest.isEmpty && !p(rest.head)) rest = rest.tail

Which causes materialization and actual filtering of the Stream . 这导致Stream实现和实际过滤。

If you want full laziness, go with withFilter : 如果你想要完全懒惰,请使用withFilter

"12334".grouped(1).toStream.withFilter { n => println("n:" +n ); n=="3"; }

For more see withFilter instead of filter . 有关详细信息,请参阅withFilter而不是filter

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM