简体   繁体   English

来自scala代码的Java 8 Stream

[英]Java 8 Stream from scala code

I'm trying to use Java 8 Stream from scala code as below and stuck with an compilation error. 我正在尝试使用scala代码中的Java 8 Stream,如下所示,并且遇到编译错误。

any help appreciated!! 任何帮助赞赏!!

def sendRecord(record: String): Unit throws Exception

bufferedReader.lines().forEach(s => sendRecord(s))

Cannot resolve forEach with such signature, expect: Consumer[_ >: String], actual: (Nothing)

PS: though there is some indication that it is almost straight forward like https://gist.github.com/adriaanm/892d6063dd485d7dd221 it doesn't seem to work. PS:虽然有一些迹象表明它几乎是直截了当的,如https://gist.github.com/adriaanm/892d6063dd485ddd221,它似乎不起作用。 I'm running Scala 2.11.8 我正在运行Scala 2.11.8

You can convert to iterator to iterate java Stream , like: 您可以转换为iterator来迭代java Stream ,如:

import scala.collection.JavaConverters._
bufferedReader.lines().iterator.asScala.forEach(s => sendRecord(s))

Look at top of the file you linked in your question. 查看您在问题中链接的文件的顶部。 It mentions -Xexperimental flag. 它提到了-Xexperimental flag。 If you run scala compiler or repl with this flag scala functions will be translated to java equivalents. 如果运行scala编译器或带有此标志的repl,则scala函数将被转换为java等效项。 Another option is to just pass in java function manually. 另一个选择是手动传入java函数。

scala> java.util.stream.Stream.of("asd", "dsa").map(new java.util.function.Function[String, String] { def apply(s: String) = s + "x" }).toArray
res0: Array[Object] = Array(asdx, dsax)

you can also create (implicit) conversion to wrap scala functions for you. 您还可以创建(隐式)转换来为您包装scala函数。

You can also wait for scala 2.12, with this version you won't need the flag anymore. 您还可以等待scala 2.12,使用此版本,您将不再需要该标志。

Update 更新

As scala 2.12 is out, the code in question would just compile normally. 当scala 2.12出来时,有问题的代码将正常编译。

The problem is that that expression in scala does not automatically implement the expected java functional interface Consumer. 问题是scala中的表达式不会自动实现预期的java功能接口Consumer。

See these questions for details how to solve it. 请参阅这些问题,了解如何解决它。 In Scala 2.12,it will probably work without conversions. 在Scala 2.12中,它可能无需转换即可运行。

In Scala 2.12 you can work with Java streams very easily: 在Scala 2.12中,您可以非常轻松地使用Java流:

import java.util.Arrays

val stream = Arrays.stream(Array(1, 2, 3, 4, 6, 7))
stream
  .map {
    case i: Int if i % 2 == 0 => i * 2
    case i: Int if i % 2 == 1 => i * 2 + 2
  }
  .forEach(println)

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

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