合并ArrayBuffer中的两个第一个和第二个元素

时间:2015-07-04 12:13:23

标签: arrays scala

我有这些ArrayBuffers:

ArrayBuffer(1.0, $, monitor, fine, couple, week, develop, expo)
ArrayBuffer(2.0, $, latest, company, follow, mercedes, unreliable, territory)
ArrayBuffer(5.0, $, plan, everyday, continually, surprised, fault)
ArrayBuffer(2.0, $, work, box, broken, turn, turn, seconds, very, frustrating) 
ArrayBuffer(7.0, $, wait, deliver, wait, deliver, doesnt, bode, well, sony)
...

我希望从这些ArrayBuffers下面创建字符串:

1.0$ monitor fine couple week develop expo
2.0$ latest company follow mercedes unreliable territory
5.0$ plan everyday continually surprised fault
2.0$ work box broken turn turn seconds very frustrating
7.0$ wait deliver wait deliver doesnt bode well sony
...

我试过了:

val ArrBuf1 = ArrayBuffer.map(_.mkString(" "))
val out = ArrBuf1.filter(_.nonEmpty)

但我的代码显示了这些结果:

1.0 $ monitor fine couple week develop expo
2.0 $ latest company follow mercedes unreliable territory
5.0 $ plan everyday continually surprised fault
...

如何合并这些Arraybuffers中的第一个和第二个元素?

2 个答案:

答案 0 :(得分:2)

替换:

_.mkString(" ")

使用:

l => l.head + l.tail.mkString(" ")

答案 1 :(得分:0)

这将有助于您需要合并集合的任何字段

代码: -

var x =List(ArrayBuffer(1.0, "$"," monitor"," fine"," couple"," week"," develop", "expo"),
ArrayBuffer(2.0, "$"," latest"," company"," follow"," mercedes"," unreliable"," territory"),
ArrayBuffer(5.0, "$"," plan"," everyday"," continually"," surprised"," fault"),
ArrayBuffer(2.0, "$"," work"," box"," broken"," turn"," turn"," seconds"," very"," frustrating"),
ArrayBuffer(7.0, "$"," wait"," deliver"," wait"," deliver"," doesnt"," bode"," well"," sony"))

var mergerAtFeild=1
x.foreach { x => x.zipWithIndex.foreach{
    f=>{
     print(if(f._2 == mergerAtFeild){f._1.toString()}else{" "+f._1.toString()})
    }
}
 print("\n")
}