左联接两个列表

时间:2019-06-24 12:11:34

标签: scala list

我想离开两个列表,而不会丢失数据。下面的示例:

// two lists
val b = List("John","Alice","Gregor","Mike")                 // base list
val l = List((List(1,2,3),"Mike"), (List(3,1,2), "Alice"))  // list to left join

// sorted
val bs = b.sorted        // List("Alice","Gregor","John","Mike")
val ls = l.sortBy(_._2)  // List((List(3,1,2), "Alice"),(List(1,2,3),"Mike"))


// left join - expected result:
// Alice and Mike found in both lists, Gregor and John appear only in the base list
// List(("Alice",(List(3,1,2),"Alice"), ("Gregor",Nil), ("John",Nil), ("Mike",List("Alice","Gregor","John","Mike"))))

我找到了一些方法,但是它们似乎不适合我:
-zip-简单的“复制/粘贴”两个列表,
-flatMap-删除两个列表中都没有出现的元素。

谢谢。

3 个答案:

答案 0 :(得分:4)

尝试

b
  .map(key => key -> l.find(_._2 == key))
  .map {case (key, value) => key -> value.getOrElse(Nil) }

输出

List((John,List()), (Alice,(List(3, 1, 2),Alice)), (Gregor,List()), (Mike,(List(1, 2, 3),Mike))

答案 1 :(得分:1)

使用此

bs.map{
  str =>
    (str, ls.find(_._2 == str).getOrElse(Nil))
}

您将得到一个输出

List((Alice,(List(3, 1, 2),Alice)), (Gregor,List()), (John,List()), (Mike,(List(1, 2, 3),Mike)))

答案 2 :(得分:1)

您可以使用Map来做到这一点:

val m = l.map(_.swap).toMap

val res = bs.map(elem => elem -> m.get(elem).map(_ -> elem).getOrElse(Nil))
println(res)
// Displays
// List((Alice,(List(3, 1, 2),Alice)), (Gregor,List()), (John,List()), (Mike,(List(1, 2, 3),Mike)))