16

Suppose I have a list of tuples

('a', 1), ('b', 2)...

How would one get about converting it to a String in the format

a 1
b 2

I tried using collection.map(_.mkString('\t')) However I'm getting an error since essentially I'm applying the operation to a tuple instead of a list. Using flatMap didn't help either

1 Answer 1

32

For Tuple2 you can use:

val list = List(("1", 4), ("dfg", 67))
list.map { case (str, int) => s"$str $int"}

For any tuples try this code:

val list = List[Product](("dfsgd", 234), ("345345", 345, 456456))

list.map { tuple => 
  tuple.productIterator.mkString("\t")
}
Sign up to request clarification or add additional context in comments.

3 Comments

will this take care of adding a \n after every tuple?
No. It maps every tuple to string. If you want \n after lines use mkString on result list.
I don't think the toList after the productIterator is necessary.

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.