简体   繁体   English

如何有效地与Scala中的Java流进行交互?

[英]How do I effectively interact with Java streams from Scala?

My code starts like this: 我的代码是这样开始的:

val paths: Array[Path] = ...
val filePaths: Array[java.util.stream.Stream[Path]] = paths.map(Files.walk(_))

Prerferably I'd like to get 'filePaths' to have type Array[Path]. 我想让'filePaths'具有Array [Path]类型。 (Any Scala collection would work just as well). (任何Scala集合都可以使用)。 But any further progress from this point on eludes me. 但是从那时起,任何进一步的进展都使我望而却步。 I've tried various combinations of JavaConversions, flatMap, reduce, collect and java.util.stream.Stream#toArray, always resulting in some obscure type error. 我尝试了JavaConversions,flatMap,reduce,collect和java.util.stream.Stream#toArray的各种组合,总是导致一些晦涩的类型错误。

Also it'd be nice to not just see a solution but also some insight into why this appears to be so much harder than it ought to be. 同样,不仅看到解决方案,而且对为什么这看起来比想象的要难得多有一些见解,这将是很好的。 For instance why doesn't 例如为什么不

import scala.collection.JavaConversions._
...
paths.flatMap(Files.walk(_))
//or
paths.flatMap(Files.walk(_).collect(Collectors.toList))

work? 工作? (The IDE error is: "exptected: (Path) => GenTraversableOnce[NotInferedB], actual: (Path) => Any") (IDE错误为:“受保护:(路径)=> GenTraversableOnce [NotInferedB],实际:(路径)=>任何”)

import scala.collection.JavaConverters._
paths.flatMap(Files.walk(_).collect(Collectors.toList[Path]).asScala)

You were on right path, toList just needed a type. 您在正确的路径上, toList仅需要一种类型。

Note that you should prefer JavaConverters to JavaConversions as it is more readble. 请注意,您应该更喜欢JavaConvertersJavaConversions因为它更具可读性。

If you use -Xexperimental you can use java api as well 如果使用-Xexperimental,则也可以使用Java api

Arrays.stream(paths).flatMap(Files.walk(_)).collect(Collectors.toList[Path]).asScala

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

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