Do peop开发者_JAVA技巧le really use Scala's Stream class in production code, or is it primarily of academic interest?
There's no problem with Stream
, except when people use it to replace Iterator
-- as opposed to replacing List
, which is the collection most similar to it. In that particular case, one has to be careful in its use. On the other hand, one has to be careful using Iterator
as well, since each element can only be iterated through once.
So, since both have their own problems, why single out Stream
's? I daresay it's simply that people are used to Iterator
from Java, whereas Stream
is a functional thing.
Even though I wrote that Iterator is what I want to use nearly all the time I do use Stream
in production code. I just don't automatically assume that the cells are garbage collected.
Sometimes Stream
fits the problem perfectly. I think the api gives some good examples where recursion is involved...
Look here. This blog post describes how to use Scala Streams (along with memory mapped file) to read large files (1-2G) efficiently.
I did not try it yet but the solution looks reasonable. Stream provides a nice abstraction on top of the low level ByteBuffer
Java API to handle a memory mapped file as a sequence of records.
Yes, I use it, although it tends to be for something like this:
(as.toStream collect expensiveConversionToB) match {
case b #:: _ => //found my expensive b
case _ =>
}
Of course, I might use a non-strict view and a find
for this example
Since the only reason not to use Stream
s is that it can be tricky to ensure the JVM isn't keeping references to early conses around, one approach I've used that's fairly nice is to build up a Stream
and immediately convert it to an Iterator
for actual use. It loses a little of Stream
's nice properties on the use side especially with respect to backtracking, but if you're only going to make one pass over the result it's frequently easier to build a structure this way than to contort into the hasNext
/next()
model of Iterator
directly.
精彩评论