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

Time:04-21

I am newbie in scala and I have a problem when merging or joining (dont know the exact term in scala) two lists by key values. In a case, key values didn't match and I took java.util.NoSuchElementException: key not found error. But I want to have just matched cases. My sample code snippet is as follows:

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))

The error message for above code is: java.util.NoSuchElementException: key not found: (2,6)

My aim is to have something like that:

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

OR

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

Is especially the first one is possible? And how can I do that?

I tried that bu it returned none:

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

If you can help, I will be appreciated

CodePudding user response:

Use 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)
  • Related