Search code examples
scala

Replace sequence of tuple value from another


val x = seq((1, 'a'), (2, 'b'))  
val y = seq((1, 'AA'), (3, 'CC'), (4, 'DD'))

Expected result

val z = seq((1, 'AA'), (2, 'b'))    

I can do it as below

x.toMap.map(k => (k._1, y.toMap.getOrElse(k._1, k._2))

But this will not preserve the order

Is there a way to do an ordered replacement


Solution

  • First, your code would work the same without the first toMap, which is not doing anything useful and is the one that is destroying the order.
    Second, you are converting y to a Map for each element of x, making this really expensive and even worse that just using find or collectFirst.
    Third, we could use some pattern matching to make the code a little bit more readable.

    // If you have a better name, feel free to change it.
    def lookupOrPreserve[K, V](
      input: Seq[(K, V)],
      lookup: Map[K, V]
    ): Seq[(K, V)] =
      input.map { case (key, originalValue) =>
        key -> lookup.getOrElse(key, default = originalValue)
      }
    
    val x = seq((1 -> 'a'), (2 -> 'b'))  
    val y = seq((1 -> 'AA'), (3 -> 'CC'), (4 -> 'DD'))
    val z = lookupOrPreserve(input = x, lookup = y.toMap)