如何将Scala流转换为Java流?

gstyhher  于 2022-12-23  发布在  Scala
关注(0)|答案(3)|浏览(195)

我有一个接收Scala Stream的Java应用程序。
我需要将其转换为Java Stream
我如何在Java* 中做到这一点?

wwtsj6pe

wwtsj6pe1#

这是一个很长的路要走,但是你可以把scala流转换成一个可迭代对象,一个java可迭代对象,然后从java可迭代对象构造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作为流的头部

vc9ivgsu

vc9ivgsu2#

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

import scala.jdk.javaapi.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
scyqe7ek

scyqe7ek3#

如果你不想并行处理流,你可以简单地子类化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。

相关问题