I am trying to understand the best way to write this. This is part of my organization work so can't disclose it fully here like why such requirement. So Apologies for that.
I have ListA and ListB.
val ListA: List[((String, String), Int)] = List(
(("A", "B"), 1),
(("C", "D"), 2),
(("E", "F"), 5),
(("E", "F"), 4),
(("E", "F"), 3)
)
val ListB: List[(String, String)] = List(
("A", "B"),
("E", "F")
)
We need to search id in ListA that contain ListB element. For example tuple ("A", "B") is present in ListA with (("A", "B"), 1), . so output would be List(1). This process would repeat again once we fetch first match. if no match is found then List(0) would be output. Also both lists are sorted on priority. ListB drives the main priority and after that in case of repeating values the List A does it. And lists are already ordered. I wrote this.
val result = ((for {
a <- ListB
m <- ListA.filter(_._1 == a).map(_._2)
} yield m):::List(0)).slice(0,1)
slice is used because we need List with first match. as ListB is already sorted on priority. Also We are going to repeat this process again by removing already matched id from ListA. But for now please ignore like how we remove these elements and re-iterate.
So new iteration would be on
val ListA: List[((String, String), Int)] = List(
// (("A", "B"), 1), This will not be part of second iteration as we already matched it in first iteration.
(("C", "D"), 2),
(("E", "F"), 5),
(("E", "F"), 4),
(("E", "F"), 3)
)
val ListB: List[(String, String)] = List(
("A", "B"),
("E", "F")
)
Output of
- iteration 1 is List(1)
- iteration 2 is List(5)
- iteration 3 is List(4)
- iteration 4 is List(3)
- iteration 5 is List(0)
I would just like to understand that
"Is it right way to code where we search one list element in another".
"Do we have some scala library that can be used here like ListA.filter(ListB.contains(_._1)) --> this needs us to write full filter case method so it wont work like this"