Scala 元组到字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26751441/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 06:40:20  来源:igfitidea点击:

scala tuple to String

scala

提问by Ashwini Khare

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 flatMapdidn't help either

我尝试使用collection.map(_.mkString('\t'))但是我收到一个错误,因为我基本上是将操作应用于元组而不是列表。使用flatMap也没有帮助

回答by Sergii Lagutin

For Tuple2you can use:

因为Tuple2您可以使用:

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