[英]Transforming Map[String, Iterator[Int]] to Iterator[Map[String, Int]]
I've run into a bit of a problem. 我遇到了一些问题。 I need to convert the types
我需要转换类型
Map[String, Iterator[Int]] -> Iterator[Map[String, Int]]
My current approach at solving this problem is by using a recursive function: 我目前解决这个问题的方法是使用递归函数:
def Inverter(input: Map[String, Iterator[Int]], output: Iterator[Map[String, Int]]) = {
val inversion: Map[String, Int] = input.flatMap {case (symbol, iterator) => iterator.hasNext match {
case true => Some((symbol,iterator.next))
case false => None
}}
inversion.size match {
case 0 => output
case _ => Inverter(input, output ++ Iterator(inversion))
}
}
This code solves the problem, but is too slow. 此代码解决了问题,但速度太慢。 I think it has something to do with the
++
call being slow. 我认为这与
++
调用缓慢有关。 Is there any way I can cons elements onto the head of an Iterator like I can a List in constant time? 有没有什么方法可以将元素集中到Iterator的头部,就像我可以在一个列表中一样? If not, can anyone come up with a good workaround?
如果没有,任何人都可以提出一个好的解决方法吗?
def invert(input: Map[String, Iterator[Int]]) =
Iterator.continually(input.collect {
case (key, it) if it.hasNext => (key, it.next)
}).takeWhile(_.nonEmpty)
Some explanation: 一些解释:
This part: input.collect { case (key, it) if it.hasNext => (key, it.next) }
takes a single element from every iterator in the input map and creates a Map[String,Int]
. 这部分:
input.collect { case (key, it) if it.hasNext => (key, it.next) }
从输入映射中的每个迭代器获取一个元素并创建Map[String,Int]
。 Now, simply apply this operation on the input map continually, until we exhaust all the iterators. 现在,只需在输入映射上连续应用此操作,直到我们耗尽所有迭代器。
It's a little tricky, because iterators are inherently mutable and we are relying on side effects of the collect
invocation. 这有点棘手,因为迭代器本质上是可变的,我们依赖于
collect
调用的副作用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.