Sebastian Oberhoff
Sebastian Oberhoff

Reputation: 1311

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]. (Any Scala collection would work just as well). 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.

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")

Upvotes: 0

Views: 66

Answers (1)

Łukasz
Łukasz

Reputation: 8673

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

You were on right path, toList just needed a type.

Note that you should prefer JavaConverters to JavaConversions as it is more readble.

If you use -Xexperimental you can use java api as well

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

Upvotes: 1

Related Questions