scala方法在Array [Seq [Object]]中隔离每种类型的对象,以分离对象引用

时间:2016-03-21 05:30:15

标签: scala

PFB案例类

class TypeData()

case class delivery(accept_language:String,customer_id:String) extends TypeData

case class junk(`type`:String) extends TypeData

我有一个对象"检查"其类型为Array[Seq[TypeData]],样本数据如下所示,

Array[Seq[TypeData]] = Array(ArrayBuffer(delivery(null,1035), delivery(null,1035), junk(injection), junk(open), junk(injection), delivery(null,1035), delivery(null,1035), delivery(null,1035), delivery(null,1035), delivery(null,1035), junk(injection), junk(injection), delivery(null,1035), junk(injection), delivery(null,1035), junk(injection), junk(injection), junk(injection), delivery(null,1035), junk(injection), junk(injection), delivery(null,1035), delivery(null,1035), junk(injection), delivery(null,1035), delivery(null,1035), delivery(null,1035), delivery(null,1035), junk(injection), junk(injection), delivery(null,1035), junk(injection), junk(click), junk(injection), delivery(null,1035), junk(injection), delivery(null,1035), delivery(null,1035), junk(open), junk(injection), deli...

现在我想知道,如何隔离每个对象类型数据以拥有自己的引用。例如,

val delivery_data = Seq[delivery]  (should contain only delivery type data) (delivery(null,1035), delivery(null,1035), delivery(null,1035), delivery(null,1035)....) and similarly

val junk_data = Seq[junk] (should contain only junk type data)
(junk(injection), junk(click), junk(injection)

此致 萨蒂亚吉特。

2 个答案:

答案 0 :(得分:1)

val a: Array[Seq[TypeData]] = ???

val (deliveries, junks) = 
  a.flatten.foldLeft((Seq.empty[delivery], Seq.empty[junk])) {
    case ((d, j), e: delivery) => (d :+ e, j)
    case ((d, j), e: junk) => (d, j :+ e)
  }

如果您只想收集货物或只收取货物,则以下方式为:

val deliveries = a.flatten collect {
  case d: delivery => d
}

val junks = a.flatten collect {
  case j: junk => j
} 

答案 1 :(得分:1)

val data: Array[Seq[TypeData]] = ???

data(0).partition(_.isInstanceOf[delivery])