replace specific values from one sequence to another

replace specific values from one sequence to another

I have 2 sequences -

val seq1 = Seq(1, 0, 3, 0)
val seq2 = Seq(10, 20, 30, 40)

I need to replace '0' values in seq1 with corresponding index values from seq2. How do I achieve this .

result = Seq(1,20,3,40)

Answer

Just zip them an pick 1 value in map

seq1.zipAll(seq2, 0, 0).map {
  case (0, i) => i // the 1st seq is 0 -> use value from another seq
  case (i, _) => i // non-0 value in the 1st seq -> use it
}

You can use views if you don't want to intermediate results

seq1.view.zipAll(seq2.view, 0, 0).map {
  case (0, i) => i // the 1st seq is 0 -> use value from another seq
  case (i, _) => i // non-0 value in the 1st seq -> use it
}.toSeq

Enjoyed this question?

Check out more content on our blog or follow us on social media.

Browse more questions