Reputation: 459
I am reading a file composed of lines in the format a=b
.
Using Source.fromFile("file").getLines
I get an Iterator[String]
. I figure I need to split the strings into tuples and then form the map from the tuples - that is easy. I am not being able to go from the Iterator[String]
to an Iterator[(String,String)]
.
How can I do this? I am a beginner to scala and not experienced with functional programming, so I am receptive to alternatives :)
Upvotes: 2
Views: 2722
Reputation: 30217
This is my try:
val strings = List("a=b", "c=d", "e=f")
val map = strings.map(_.split("=")).map { case Array(f1,f2) => (f1,f2) }
Upvotes: 0
Reputation: 391
Maybe like this?
Source.fromFile("file").getLines.map(_.split("=").map( x => (x.head,x.tail) ) )
You might want to wrap this into Try
.
Upvotes: 0
Reputation: 149646
You can do so by splitting the string and then creating the tuples from the first and second elements using Iterator.map
:
val strings = List("a=b", "c=d", "e=f").iterator
val result: Iterator[(String, String)] = strings.map { s =>
val split = s.split("=")
(split(0), split(1))
}
If you don't mind the extra iteration and intermediate collection you can make this a little prettier:
val result: Iterator[(String, String)] =
strings
.map(_.split("="))
.map(arr => (arr(0), arr(1)))
Upvotes: 1
Reputation: 2115
You can transform the values returned by an Iterator using the map
method:
def map[B](f: (A) ⇒ B): Iterator[B]
Upvotes: 0