我想左连接两个列表,而不丢失数据。下面的例子:
// 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 - 删除没有出现在两个列表中的元素。
先感谢您。
最佳答案
尝试
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))
关于scala - 左连接两个列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56736288/