2

在集合中查找元素索引的优雅方法是什么?现在我实现了这样的方法:

  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
  }

可以用更优雅的方式重写吗?谢谢

4

1 回答 1

2

只是

collection.indexOf(value)

请注意,如果集合不是 Seq 的子类型,则索引没有意义。

如果你真的想获得index任何收藏,你可以使用

collection.toSeq.indexOf(value)

查找此列表中某个值在某个起始索引之后或处第一次出现的索引。elem 要搜索的元素值。from start index 返回此列表中等于(由 == 确定)到 elem 的第一个元素的索引 >= from,如果不存在,则返回 -1。

于 2013-07-21T11:31:52.383 回答