Scala两个列表匹配数据

时间:2014-11-07 08:14:20

标签: scala scala-collections

首先列出数据如下

List(("A",66729122803169854198650092,"SD"),("B",14941578978240528153321786,"HD"),("C",14941578978240528153321786,"PD"))

和第二个列表包含以下数据

List(("X",14941578978240528153321786),("Y",68277588597782900503675727),("Z",14941578978240528153321786),("L"66729122803169854198650092))

使用上面的两个列表我想形成以下列表,它将第一个列表第二个数字与第二个列表第二个数字相匹配,所以我的输出应该如下所示

List(("X",14941578978240528153321786,"B","HD"),("X",14941578978240528153321786,"C","PD"),   ("Y",68277588597782900503675727,"",""),("Z",14941578978240528153321786,"B","HD"),("Z",14941578978240528153321786,"C","PD"),
("L",66729122803169854198650092,"A","SD"))

1 个答案:

答案 0 :(得分:2)

val tuples3 = List(
  ("A", "66729122803169854198650092", "SD"),
  ("B", "14941578978240528153321786", "HD"),
  ("C", "14941578978240528153321786", "PD"))

val tuples2 = List(
  ("X", "14941578978240528153321786"),
  ("Y", "68277588597782900503675727"),
  ("Z", "14941578978240528153321786"),
  ("L", "66729122803169854198650092"))

按目标字段分组第一个列表:

val tuples3Grouped =
  tuples3
    .groupBy(_._2)
    .mapValues(_.map(t => (t._1, t._3)))
    .withDefaultValue(List(("", "")))

压缩所有数据:

val result = for{ (first, second) <- tuples2
     t <- tuples3Grouped(second)
} yield (first, second, t._1, t._2)