I have a requirement where I have to convert a Iterator[Long] to Iterator[String] in scala. Please let me know how can I do it
Asked
Active
Viewed 724 times
0
-
Q&A for producing a true `Iterator[Long]` posted [here](https://stackoverflow.com/questions/72937656/how-to-produce-a-true-iterarorlong-in-scala/72937657#72937657) – Darren Bishop Jul 11 '22 at 11:15
2 Answers
1
Well just like any other collection use map. For example:
scala> val ls = List(1,2,3).toIterator
ls: Iterator[Int] = non-empty iterator
scala> ls.map(_.toString) //it was map(x+""). see comments on why it is bad
res0: Iterator[String] = non-empty iterator
scala> res0.next
res1: String = 1
scala> res0.next
res2: String = 2
scala> res0.next
res3: String = 3

Jatin
- 31,116
- 15
- 98
- 163
-
-
Ugh, `+""` is awkward, unclear, and relies on [one of the worst parts](https://issues.scala-lang.org/browse/SI-194) of the Scala language. `ls.map(_.toString)` would be at least a little less horrible. – Travis Brown Mar 10 '14 at 06:16
-
1
scala> List(1,2,3).toIterator.map(_.toString)
res1: Iterator[String] = non-empty iterator
scala> List(1,2,3).toIterator.map(_.toString).mkString(", ")
res2: String = 1, 2, 3

Mike Slinn
- 7,705
- 5
- 51
- 85