如何将Java流转换为Scala流? [英] How to convert a Java Stream to a Scala Stream?

查看:175
本文介绍了如何将Java流转换为Scala流?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为将Java代码转换为Scala代码的一部分,我需要将Java流Files.walk(Paths.get(ROOT))转换为Scala.我无法通过谷歌搜索找到解决方案. asScala不会这样做.有提示吗?

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?

以下是相关代码:

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

其中Files.walk(Paths.get(ROOT))返回类型在Java中为Stream<Path>.

where the Files.walk(Paths.get(ROOT)) return type is Stream<Path> in Java.

推荐答案

还有一种更好的方法,不需要提到compat层或实验性2.11功能 @marcospereira

There is a slightly nicer way without needing the compat layer or experimental 2.11 features mentioned here by @marcospereira

基本上只使用迭代器:

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

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

这篇关于如何将Java流转换为Scala流?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆