Java - 如何将Scala Stream转换为Java Stream?

时间:2015-11-25 15:13:16

标签: java scala scala-java-interop

我有一个Java应用程序,它接收default

我需要将其转换为Scala Stream

我如何在Java 中执行

3 个答案:

答案 0 :(得分:4)

这是一个很长的路要走,但你可以将scala流转换为iterable,转换为java iterable,然后从java iterable构造java流:

scala>
import java.util.stream.StreamSupport
import scala.collection.JavaConverters._

def stream2javaStream[T](scalaStream: scala.Stream[T]): java.util.stream.Stream[T] = {
    StreamSupport.stream(scalaStream.toIterable.asJava.spliterator(), false);
}


stream2javaStream((1 to 100).toStream)

res0: java.util.stream.Stream[Int] = java.util.stream.ReferencePipeline$Head@2489e84a

虽然环形交叉,但这并没有实现"流,保持其效率。

scala>
stream2javaStream((1 to 100).toStream.map{i => println(i); i})
1
res1: java.util.stream.Stream[Int] = java.util.stream.ReferencePipeline$Head@9b21bd3

仅为流的头部打印1

答案 1 :(得分:0)

如果您不想并行处理流,则可以将AbstractSpliterator子类化:

import java.util.function.Consumer
import java.util.stream.StreamSupport
import java.util.{Spliterator, Spliterators}

def streamToJava[T](s: Stream[T]): java.util.stream.Stream[T] = {
    var ss: Stream[T] = s
    val splitr = new Spliterators.AbstractSpliterator[T](Long.MaxValue, Spliterator.IMMUTABLE) {
      override def tryAdvance(action: Consumer[_ >: T]): Boolean = ss match {
        case Stream.Empty => false
        case h #:: tl => {ss = tl; action.accept(h); true}
      }
    }
    StreamSupport.stream(splitr, false)
  }

另一个答案(我太新了,不能评论),因为它调用size来实现整个流,因此不正确。

答案 2 :(得分:0)

Scala 2.13开始,标准库包括scala.jdk.StreamConverters,该库提供Java到Scala的隐式流转换:

import scala.jdk.StreamConverters;

// val scalaStream = Stream(1, 2, 3)
StreamConverters.asJavaSeqStream(scalaStream);
// java.util.stream.Stream[Int] = java.util.stream.ReferencePipeline$Head@3cccf515

请注意,在Scala 2.13中Stream被重命名为LazyList,在这种情况下:

// val scalaLazyList = LazyList(1, 2, 3)
StreamConverters.asJavaSeqStream(scalaLazyList);
// java.util.stream.Stream[Int] = java.util.stream.ReferencePipeline$Head@4997c13