Ashwini Khare Ashwini Khare - 4 months ago 30
Scala Question

scala tuple to String

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

Answer

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