Let's say I have a list:
val list = List(1,2,3,4,5)
I want to replace all / first elements that satisfy the predicate, I know the following way to do this: (for example, replace any number that even with -1)
val filteredList = list.zipWithIndex.filter(_._2 % 2 == 0) val onlyFirst = list.updated(filteredList.head._2, -1) val all = for(i <- list) yield if(i % 2 ==0) -1 else i
Is there any collection feature or a good Scala way that helps in this situation and has good performance ?
I also want to keep order, so I don't want to use filterNot and add other elements to the list like: (it is also inefficient)
val onlyFirst = list.filterNot(_ % 2 != 0) ::: list.filter(_ % 2 == 0).map(x => -1)
source share