Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I change only one element of a Seq?

I have an immutable Seq. I need to create a new Seq from it, with only one element changed, whose index is given to me. How can I do it ? (I think since the sequence is immutable I will need to use some function and create a new output sequence, but I do not know how to check index for conditional update in the "map" function.) Thanks

like image 685
potato Avatar asked Oct 24 '25 14:10

potato


1 Answers

If the element has to be transformed with some function f then

val idx = 2 // given index to transform

mySeq.iterator.zipWithIndex.map { 
  case (e, `idx`) => f(e)
  case (e, _) => e
}.toSeq

If it just needs to be replaced with another given element then

mySeq.updated(idx, newElement)

If collection will be frequently updated then consider Vector instead because List which is the default implementation of Seq is not optimised for updates.

like image 183
Mario Galic Avatar answered Oct 26 '25 12:10

Mario Galic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!