Scala 函数的函数接口 - scala-java8-compat
大多数示例都是从自述文件复制的
scala.FunctionN 和 java.util.function 之间的转换器
import java.util.function._
import scala.compat.java8.FunctionConverters._
val foo: Int => Boolean = i => i > 7
def testBig(ip: IntPredicate) = ip.test(9)
println(testBig(foo.asJava)) // Prints true
val bar = new UnaryOperator[String]{ def apply(s: String) = s.reverse }
List("cod", "herring").map(bar.asScala) // List("doc", "gnirrih")
def testA[A](p: Predicate[A])(a: A) = p.test(a)
println(testA(asJavaPredicate(foo))(4)) // Prints false
scala.Option 和 java.util 类之间的转换器可选,OptionalDouble,OptionalInt 和 OptionalLong
import scala.compat.java8.OptionConverters._
class Test {
val o = Option(2.7)
val oj = o.asJava // Optional[Double]
val ojd = o.asPrimitive // OptionalDouble
val ojds = ojd.asScala // Option(2.7) again
}
从 Scala 集合转换为 Java 8 Streams
import java.util.stream.IntStream
import scala.compat.java8.StreamConverters._
import scala.compat.java8.collectionImpl.{Accumulator, LongAccumulator}
val m = collection.immutable.HashMap("fish" -> 2, "bird" -> 4)
val parStream: IntStream = m.parValueStream
val s: Int = parStream.sum
// 6, potientially computed in parallel
val t: List[String] = m.seqKeyStream.toScala[List]
// List("fish", "bird")
val a: Accumulator[(String, Int)] = m.accumulate // Accumulator[(String, Int)]
val n = a.stepper.fold(0)(_ + _._1.length) +
a.parStream.count // 8 + 2 = 10
val b: LongAccumulator = java.util.Arrays.stream(Array(2L, 3L, 4L)).accumulate
// LongAccumulator
val l: List[Long] = b.to[List] // List(2L, 3L, 4L)