按时间组合scala案例类列表并构造案例类的新列表

时间:2018-02-23 17:59:16

标签: scala collections

trait MetaData {
    def time:DateTime
}

case class ImageMetadata(time: DateTime, name: String) extends MetaData
case class ObjectMetadata(time: DateTime, tags: List[String]) extends MetaData
case class ImageTypeMetadata(time: DateTime, name: String, tags: List[String])

我有一个返回Future[List[ImageMetadata]]Future[List[ObjectMetadata]]的方法;我想在timeImageMetadata的{​​{1}}字段中合并这两个列表,并希望构建ObjectMetadata

我可以选择最好的选项吗?

1 个答案:

答案 0 :(得分:0)

以下是如何在没有Future的情况下组合两个集合:

由于我的Scala缺少DateTime,但我总是需要具体的测试示例,我将DateTime重新定义为String。您不会使用该类型声明。 :)

type DateTime=String

sealed trait MetaData {
    def time:DateTime
}
case class ImageMetadata (time: DateTime, name: String) extends MetaData
case class ObjectMetadata (time: DateTime, tags: List[String]) extends MetaData
case class ImageTypeMetadata (time: DateTime, name: String, tags: List[String])

val la = List (ImageMetadata("12", "im 1 foo"), ImageMetadata ("13", "im 2 bar"), ImageMetadata ("23", "im 3 bar"))
val lb = List (ObjectMetadata("23", List ("o", "1")), ObjectMetadata ("12", List("o", "2")), ObjectMetadata ("17", List("o", "3")))

import concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global

val flim : Future [List [ImageMetadata]] = Future (la)
val flom : Future [List [ObjectMetadata]] = Future (lb)
flim.map (_.map (im => flom.map (_.map (om => {if (im.time == om.time)  Future (ImageTypeMetadata (im.time, im.name, om.tags))}))))

这对于列表期货做同样的事情有帮助吗? 嗯,这很直接:

SELECT y.group, id, submit_date, coalesce( SUM( amt ), 0 ) As Total_due_so_far
FROM (
   SELECT x.group, id, submit_date,
          ( SELECT amount FROM table2 t2
            WHERE t2.id = id12
            AND t2.as_date <= x.submit_dateeee
            ORDER BY as_date DESC
            LIMIT 1
           ) As amt
    FROM (
      SELECT t11.group, t11.id as id, t11.submit_date, t12.id as id12,
             max( t2.as_date ) as submit_dateeee
      FROM table1 t11
      LEFT JOIN table1 t12
      ON t11.id <> t12.id AND t11.submit_date > t12.submit_date AND t11.group = t12.group
      LEFT JOIN table2 t2
      ON t2.id = t12.id AND t2.as_date < t11.submit_date
      GROUP BY t11.id, t11.submit_date, t12.id
   ) x
) y
GROUP BY y.group, id, submit_date
order by 1,2
;