2

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 :)

4 Answers 4

1

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)))
Sign up to request clarification or add additional context in comments.

Comments

0

You can transform the values returned by an Iterator using the map method:

def map[B](f: (A) ⇒ B): Iterator[B]

1 Comment

I am so very sorry but do not understand your answer
0

Maybe like this?

Source.fromFile("file").getLines.map(_.split("=").map( x => (x.head,x.tail) ) )

You might want to wrap this into Try.

1 Comment

Maybe also use mkString("=") on the tail, so you are sure you have (String,String), no matter how many splits there were.
0

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) }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.