Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading