本文介绍了如何使用Java 8从Scala 2.11收集数据流?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这段代码:
import java.util.stream._
import java.util.function._
final case class AbcTest(value: String)
def funToFunction[InT, OutT](fun: InT => OutT): Function[InT, OutT] = new Function[InT, OutT] {
override def apply(t: InT): OutT = fun(t)
}
def main(args: Array[String]): Unit = {
Stream.of("a", "b", "c")
.map[AbcTest](funToFunction((v: String) => AbcTest(v)))
.collect(Collectors.toList())
}
它失败并显示以下错误消息:
And it fails with this error message:
Error:(43, 27) type mismatch;
found : java.util.stream.Collector[Nothing,?0(in method main),java.util.List[Nothing]] where type ?0(in method main)
required: java.util.stream.Collector[_ >: test.AbcTest, ?, ?]
Note: Nothing <: Any, but Java-defined trait Collector is invariant in type T.
You may wish to investigate a wildcard type such as `_ <: Any`. (SLS 3.2.10)
.collect(Collectors.toList)
我不明白发生了什么,请帮忙.
I don't understand what's happening, please help.
推荐答案
从我所看到的以下内容来看,效果很好,请记住只是在某种类型推断方面有所帮助
Well... from what I have seen the following works absolutely fine, remember to just help a little in some type inferencing
import java.util.{stream => jStream}
import java.util.{function => jFunction}
def funToFunction[InT, OutT](fun: InT => OutT): jFunction.Function[InT, OutT] =
new jFunction.Function[InT, OutT] {
override def apply(t: InT): OutT = fun(t)
}
final case class AbcTest(value: String)
val javaList =
jStream.Stream.of("a", "b")
.map[AbcTest](funToFunction((s: String) => AbcTest(s)))
.collect(jStream.Collectors.toList[AbcTest])
这篇关于如何使用Java 8从Scala 2.11收集数据流?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!