在 Scala 集合中查找和替换项目 [英] Find and Replace item in Scala collection

查看:38
本文介绍了在 Scala 集合中查找和替换项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个列表:

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

我想替换满足谓词的所有/第一项,我知道以下方法:(例如,用 -1 替换任何偶数)

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

是否有任何集合函数或不错的 Scala 方法可以帮助解决这种情况并具有良好的性能?

Is there any collection function or nice Scala way that helps in this situation and has a good performance?

我也想保留订单,所以我不想使用 filterNot 并将其他项目添加到列表中,例如:(这也没有效率)

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)

推荐答案

Simple &高效的:替换所有项目

Simple & efficient: Replace all items

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

更换一件商品

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

这篇关于在 Scala 集合中查找和替换项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆