我想知道将元素数组转换为String的最佳方法是什么时候我想做一些特定的元素。 比如说我有
case class A(x: Int, y: Int) val list = List(A(2, 3), A(4, 2), A(5, 1))现在说我想要例如将其转换为仅包含x值的逗号分隔列表。 即,“2,4,2”。 有没有办法用mkString实现这个目标?
一个相关的问题是如何处理列表中的列表。 所以说我们有:
case class A(x: Int, y: Int, bs: List(B)) case class B(z: Int)以下列表:
val list = List(A(2, 3, List(B(4), B(2))), A(4, 2, List()), A(5, 1, List(B(3))))我想输出A的部分结合说B中的第一个元素来产生类似的东西:“2:4,”4:“,”5:3“。
有没有办法用mkString实现这个目标,还是我咆哮着错误的树?
谢谢Des
I am wondering what the best approach to converting an array of elements to String is when I want to do something specific to the elements. For example say I have
case class A(x: Int, y: Int) val list = List(A(2, 3), A(4, 2), A(5, 1))Now say I wanted for example to convert this to a comma separated list of only the x values. ie, "2, 4, 2". Is there a way to achieve this with mkString?
And a related question is how to handle lists within lists. So say we have:
case class A(x: Int, y: Int, bs: List(B)) case class B(z: Int)and the following list:
val list = List(A(2, 3, List(B(4), B(2))), A(4, 2, List()), A(5, 1, List(B(3))))and I want to output parts of A combined with say the first element in B to produce something like: "2:4, "4:", "5:3".
Is there a way of achieving this with mkString or am I barking up the wrong tree?
Thanks Des
最满意答案
当然,你可以先映射然后再制作字符串:
val remapped = myList map { case A(x, y) => "%s:%s" format (x, y) } remapped mkString (",")这会产生“1:2,2:5”格式。 如果你只想用逗号分隔,那么你可以使用flatMap:
val remapped = myList flatMap{ case A(x, y) => List(x, y) } remapped mkString (",")这会给你“1,2,2,5”。
你mkString直接做到这mkString吗? 不,我不相信,除非你覆盖A的toString方法,如下所示:
case class A(x: Int, y: Int){ override def toString() = "%s:%s" format (x, y) }对于嵌套列表
使用unapply你必须更有创意:
myList map { case A(x, _, head :: _) => "%s:%s" format (x, head.z) case A(x, _, Nil) => x toString () }其中你正在提取B嵌套列表的第一项。
Sure, you can map first and then make string:
val remapped = myList map { case A(x, y) => "%s:%s" format (x, y) } remapped mkString (",")this produces "1:2, 2:5" formatting. If you just want comma delimited then you could flatMap:
val remapped = myList flatMap{ case A(x, y) => List(x, y) } remapped mkString (",")which will give you "1, 2, 2, 5".
Can you directly do this with just mkString? No, I don't believe so unless you overwrote the toString method of A like so:
case class A(x: Int, y: Int){ override def toString() = "%s:%s" format (x, y) }For nested lists
You'll have to get a little more creative with the unapply:
myList map { case A(x, _, head :: _) => "%s:%s" format (x, head.z) case A(x, _, Nil) => x toString () }wherein you're extracting the first item of the nested list of B.
更多推荐
发布评论