1

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()) 
1
  • 1
    Your for version is very odd. You don't need the if - the for already handles that, and you yield a separate Map for each entry, instead ot just the tuple. {for (i <- it) yield (i -> i.length)}.toMap would do it. Commented Feb 17, 2017 at 13:18

1 Answer 1

9

You can just use map:

val m = it.map(c => c -> c.length).toMap 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.