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.
If I use the for yield
statement the returning object would be a Iterator[Map]
and I do not want that:
val m = for(i<- it if it.hasNext) yield Map(i->i.length())
您可以只使用地图:
val m = it.map(c => c -> c.length).toMap
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.