Find and Replace item in Scala collection

旧巷老猫 提交于 2020-01-02 01:30:30

问题


Let's say I have a list:

val list = List(1,2,3,4,5)

I want to replace all/first items that satisfy a predicate, I know the following way to do it: (e.g. replace any number that is 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 function or nice Scala way that helps in this situation and has a good performance?

I also want to keep the order, so I don't want to use filterNot and add other items to the list like: (it's also not efficient)

val onlyFirst = list.filterNot(_ % 2 != 0) ::: list.filter(_ % 2 == 0).map(x => -1)

回答1:


Simple & efficient: Replace all items

list.map( x => if (x % 2 == 0) -1 else x )

Replace one item

val index = list.indexWhere( _ % 2 == 0 )
list.updated(index, -1)


来源:https://stackoverflow.com/questions/33788185/find-and-replace-item-in-scala-collection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!