查找集合中元素索引的优雅方法是什么?现在我实现了这样的方法:
def getIndexForValue[T] (value: T, collection: Iterable[T]): Option[Int] = {
val pair = collection.zipWithIndex.find(_._1 == value)
if (pair.isDefined) Some(pair.get._2) else None
}
可以用更优雅的方式重写吗?谢谢
最佳答案
只是
collection.indexOf(value)
请注意,如果集合不是 Seq 的子类型,则索引没有任何意义。
如果您确实想获取任何集合的索引
,您可以使用
collection.toSeq.indexOf(value)
查找此列表中某个值在某个起始索引之后或处首次出现的索引。 埃莱姆 要搜索的元素值。 从 起始索引 返回 该列表中第一个等于(由 == 确定)到 elem 的元素的索引 >= from,如果不存在,则为 -1。
关于scala - 获取 Iterable 的元素索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17771831/