在 Scala 中加入两个列表时如何处理不匹配的键

How to handle not matching keys when joining two lists in scala

我是 scala 的新手,在按键值合并或加入(不知道 scala 中的确切术语)两个列表时遇到问题。在一个案例中,键值不匹配,我得到了 java.util.NoSuchElementException: key not found 错误。但我只想匹配案例。我的示例代码片段如下:

val users = List(
  (1,1,4.0),
  (1,3,4.0),
  (1,6,4.0)
)

val cars = List(
  (1,1,"ww"),
  (1,3,"mds"),
  (2,6,"pgt")
)

val usersmapped = users.map(i => ((i._1,i._2),i)).toMap
val carsmapped = cars.map(i => ((i._1,i._2),i)).toMap
val result  = carsmapped.map(ar => (ar._2,usersmapped(ar._1)._3))

以上代码的错误信息是:java.util.NoSuchElementException: key not found: (2,6)

我的目标是拥有这样的东西:

List(
(1,1,ww) -> 4.0, 
(1,3,mds)-> 4.0
)

List(
(1,1,ww) -> 4.0, 
(1,3,mds) -> 4.0,
(1,6,null) -> 4.0  //null means no match with other list 
)

尤其是第一个可以吗?我该怎么做?

我试过了,但它返回了 none:

  val result  = Try(carsmapped.map(ar => (ar._2,usersmapped(ar._1)._3)))
  ).toOption

如有帮助,将不胜感激

使用get method instead of "()". get method returning Option:

val users = List(
  (1,1,4.0),
  (1,3,4.0),
  (1,6,4.0)
)

val cars = List(
  (1,1,"ww"),
  (1,3,"mds"),
  (2,6,"pgt")
)

val usersmapped = users.map(i => ((i._1,i._2),i)).toMap
val carsmapped = cars.map(i => ((i._1,i._2),i)).toMap

carsmapped
  .map(ar => (ar._2, usersmapped.get(ar._1).map(_._3)))
  .foreach(println)