Camandros
Camandros

Reputation: 459

split strings in array and convert to map

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

Answers (4)

freedev
freedev

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

holothuroid
holothuroid

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

Yuval Itzchakov
Yuval Itzchakov

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

Wilco Greven
Wilco Greven

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

Related Questions