简体   繁体   English

Scala-将迭代器转换为地图

[英]Scala - Transform a Iterator into a Map

How to get from an Iterator like this 如何从这样的迭代器获取

val it = Iterator("one","two","three","four","five")

a map like 像这样的地图

Map(four -> 4, three -> 5, two -> 3, five -> 4, one -> 3)

 var m = Map[String, Int]()
      while (it.hasNext) {
        val cell = it.next()
        m += (cell -> cell.length())
      }

this is a solution using var but I'd like to use just Immutable and val variable. 这是使用var的解决方案,但我只想使用Immutable和val变量。

If I use the for yield statement the returning object would be a Iterator[Map] and I do not want that: 如果我使用for yield语句,则返回的对象将是Iterator[Map] ,但我不希望这样:

val m = for(i<- it if it.hasNext) yield Map(i->i.length())

您可以只使用地图:

val m = it.map(c => c -> c.length).toMap

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM