0

I have two lists

val list1 = List((List("AAA"),"B1","C1"),(List("BBB"),"B2","C2"))
val list2 = List(("AAA",List("a","b","c")),("BBB",List("c","d","e")))

I want to match first element from list2 with first element of list1 and get combined list. I want output as -

List((List("AAA"),"B1","C1",List("a","b","c")))

How to get above output using Scala??

Vishwas
  • 6,967
  • 5
  • 42
  • 69
Neo-coder
  • 7,715
  • 4
  • 33
  • 52
  • list2 isn't a valid list; perhaps you could fix that and we can go from there? Specifically, those square brackets make no sense in that context. – jamesmulcahy Nov 21 '14 at 10:28
  • Can you please see my edit now.. – Neo-coder Nov 21 '14 at 10:33
  • Could you provide more examples or rephrase what you want? "first element from list2 with first element of list1 and get combined list" will be List((List("AAA"),"B1","C1"), ("AAA",List("a","b","c"))) and not the list you gave. – red1ynx Nov 21 '14 at 11:43

2 Answers2

0

This is what I came up with:

scala> val l1 = List((List("AAA"),"B1","C1"),(List("BBB"),"B2","C2"))
l1: List[(List[String], String, String)] = List((List(AAA),B1,C1), (List(BBB),B2,C2))

scala> val l2 = List((List("AAA"), List("a", "b", "c")), (List("BBB"), List("c", "d", "e")))
l2: List[(String, List[String])] = List((AAA,List(a, b, c)), (BBB,List(c, d, e)))

scala>  l1.collectFirst {
     |    case tp => l2.find(tp2 => tp2._1.head == tp._1.head).map(founded => (tp._1, tp._2, tp._3, founded._2))
     |  }.flatten
res2: Option[(List[String], String, String, List[String])] = Some((List(AAA),B1,C1,List(a, b, c)))

You can use collectFirst to filter values you don't want and on every tuple you use find on the second list and map it into the tuple you want.

A couple of notes, this is horrible, I don't know how you got with a Tuple4 in the first place, I personally hate all that tp._* notation, it's hard to read, think about using case classes to wrap all that into some more manageable structure, second I had to use .head which in case of empty list will throw an exception so you may want to do some checking before that, but as I said, I would completely review my code and avoid spending time working on some flawed architecture in the first place.

Ende Neu
  • 15,581
  • 5
  • 57
  • 68
0

You can use zip to combine both the list

val list1 = List((List("AAA"),"B1","C1"),(List("BBB"),"B2","C2"))
val list2 = List(("AAA",List("a","b","c")),("BBB",List("c","d","e")))

val combinedList = (list1 zip list2) 
combinedList.head will give you the desired result

It will give the combined list from which you can get the first element

Atiq
  • 396
  • 1
  • 3
  • 10