How to convert a Java Stream to a Scala Stream?

TeeKai picture TeeKai · Jul 12, 2016 · Viewed 16.2k times · Source

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.

Answer

mirosval picture mirosval · Aug 4, 2016

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:

import java.nio.file.{Files, Paths}
import scala.collection.JavaConverters._

Files.list(Paths.get(".")).iterator().asScala