As a part of an effort of converting Java code to Scala code, I need to convert the Java stream Files.walk(Paths.get(ROOT))
to Scala. I can't find a solution by googling. asScala
won't do it. Any hints?
The followings is the related code:
import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo;
import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.stream.Collectors;
....
Files.walk(Paths.get(ROOT))
.filter(path -> !path.equals(Paths.get(ROOT)))
.map(path -> Paths.get(ROOT).relativize(path))
.map(path -> linkTo(methodOn(FileUploadController.class).getFile(path.toString())).withRel(path.toString()))
.collect(Collectors.toList()))
where the Files.walk(Paths.get(ROOT))
return type is Stream<Path>
in Java.
Java 8 Streams and Scala Streams are conceptually different things; the Java 8 Stream is not a collection, so the usual collection converter won't work. You can use the scala-java8-compat (github) library to add a
toScala
method to Java Streams:You can't really use this conversion (Java->Scala) from Java, so if you have to do this from Java, it's easier (but still awkward) to just run the stream and build the Scala Stream yourself (which is what the aforementioned library is doing under the hood):
However, both ways will fully consume the Java Stream, so you don't get the benefit of the lazy evaluation by converting it to a Scala Stream and might as well just convert it directly to a Vector. If you just want to use the Scala function literal syntax, there different ways to achieve this. You could use the same library to use function converters, similar to collection converters:
Alternatively since 2.11, Scala has experimental support for SAM types under the
-Xexperimental
flag. This will be non-experimental without a flag in 2.12.Starting
Scala 2.13
, the standard library includesscala.jdk.StreamConverters
which provides Java to Scala implicit stream conversions:Note the usage of
LazyList
(as opposed toStream
) asStream
s have been renamedLazyList
inScala 2.13
.There is a slightly nicer way without needing the compat layer or experimental 2.11 features mentioned here by @marcospereira
Basically just use an iterator: