Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala Tuple to String (using mkString)

Tags:

scala

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

like image 643
Ashwini Khare Avatar asked Nov 05 '14 07:11

Ashwini Khare


People also ask

What is mkString in Scala?

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

Is tuple immutable in Scala?

In Scala, a tuple is a value that contains a fixed number of elements, each with its own type. Tuples are immutable.

What is string * in Scala?

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.


1 Answers

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")
}
like image 198
Sergii Lagutin Avatar answered Oct 06 '22 01:10

Sergii Lagutin