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
The mkString() method is utilized to display all the elements of the list in a string along with a separator. Method Definition: def mkString(sep: String): String. Return Type: It returns all the elements of the list in a string along with a separator. Example #1: // Scala program of mkString()
In Scala, a tuple is a value that contains a fixed number of elements, each with its own type. Tuples are immutable.
Scala string is an immutable object that means the object cannot be modified. Each element of a string is associated with an index number. The first character is associated with the number 0, the second with the number 1, etc. Class java. lang.
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")
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With