我遇到了麻烦"离开加入"在斯卡拉。例如,
val order: Array[Array[String]] = Array(Array("o2","ad1"), Array("o1","ad2"))
val line: Array[Array[String]] = Array(Array("l1","o1","x"),Array("l2","o2","y"))
期望的输出:
Array(Array("l1","o1","x","ad2"),Array("l2","o2","y","ad1"))
答案 0 :(得分:1)
数据的建模质量有问题:为什么要将所有内容表示为String数组?但是,好的,你走了:
val order: Array[Array[String]] = Array(
Array("o2","ad1"),
Array("o1","ad2"),
Array("o7","ad5")
)
val line: Array[Array[String]] = Array(
Array("l1","o1","x"),
Array("l2","o2","y"),
Array("l3","o13","z")
)
val orderAsMap = order.map{x => (x(0), x(1))}.toMap
val leftOuterJoin = for (x <- line) yield (x :+ orderAsMap.getOrElse(x(1), "<NULL>"))
// print to see the result
for (row <- leftOuterJoin) println(row.mkString(", "))
// output:
//
// l1, o1, x, ad2
// l2, o2, y, ad1
// l3, o13, z, <NULL>
中间toMap
是必要的,这样您就不必每次都遍历整个数组。实际加入是使用:+
运算符完成的。
如果您必须定期处理此类问题,请考虑使用适当的库。
编辑:感谢@igorpcholkin提醒我&#34;离开加入&#34;是&#34;左外连接&#34;的同义词在通常的命名法中。第一个版本更像是内部联接。我会把它留在这里以防万一你想要一个内部联接:
val order: Array[Array[String]] = Array(Array("o2","ad1"), Array("o1","ad2"))
val line: Array[Array[String]] = Array(
Array("l1","o1","x"),
Array("l2","o2","y"),
Array("l3","o13","z")
)
val orderAsMap = order.map{x => (x(0), x(1))}.toMap
val lj = for {
x <- line
if orderAsMap.contains(x(1))
} yield (x :+ orderAsMap(x(1)))
// print to see the result
for (row <- lj) println(row.mkString(", "))
// output:
//
// l1, o1, x, ad2
// l2, o2, y, ad1