[英]Looping over a stream in Scala
这是一个Scala类:
class CustomizedStream[K,V](private val queue: BlockingQueue[FetchedDataChunk],
FooTimeoutMs: Int,
private val keyDecoder: Decoder[K],
private val valueDecoder: Decoder[V],
val clientId: String)
extends Iterable[MessageAndMetadata[K,V]] with java.lang.Iterable[MessageAndMetadata[K,V]] {
...
}
和在Java代码中
Map<String, List<FoStream<byte[], byte[]>>> foStreams = consumer
.createMessageStreams(topicCount);
List<CustomizedStream<byte[], byte[]>> streams = consumerStreams.get(topic);
for (final CustomizedStream stream : streams) {
FoIterator<byte[], byte[]> it = stream.iterator();
while (it.hasNext()) {
System.out.println(it.next().message());
}
}
如何在Scala中重写上述Java代码? 我尝试for(stream <-stream)并得到
value foreach is not a member of java.util.List[CustomizedStream(Array[Byte], Array[Byte]]]
Łukasz建议以下解决方案:
for{
stream <- streams.asScala
m <- stream
}{
println(m)
}
我看不到任何输出,并且对于
for{
stream <- streams.asScala
} {
println(stream) // <- this line shows up
for(m <- stream){
println(m)
}
}
和相同的
val foStreams = consumer.createMessageStreams(topicCount);
val streams : java.util.List[KafkaStream[Array[Byte], Array[Byte]]]= foStreams.get(topic);
val itr = streams.iterator()
while(itr.hasNext){
val a = itr.next()
println(a) // <- can see this line
val itr2 = a.iterator()
while(itr2.hasNext()) {
println(itr2.next()) // but not this line
}
}
您不想在这里循环流,而是在包含CustomizedStream
的java.util.List
上循环。 它包含的内容无关紧要。
显而易见的方法是将Java列表转换为scala seq。
import scala.collection.JavaConverters._
val streams: java.util.List[CustomizedStream[Array[Byte], Array[Byte]]] = ???
for (stream <- streams.asScala) {
// .. code
}
由于CustomizedStream
实现了scala Iterable
您可以将Java代码简化为
for {
stream <- streams.asScala
m <- stream
} {
println(m.message)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.