Scala 检查列表中是否存在元素

我需要检查一个字符串是否出现在一个列表中,并调用一个相应地接受布尔值的函数。

有没有可能用一行程序实现这一点?

下面的代码是我能得到的最好的代码:

val strings = List("a", "b", "c")
val myString = "a"


strings.find(x=>x == myString) match {
case Some(_) => myFunction(true)
case None => myFunction(false)
}

我确信用更少的代码做到这一点是可能的,但是我不知道怎么做!

175312 次浏览

Just use contains

myFunction(strings.contains(myString))

And if you didn't want to use strict equality, you could use exists:


myFunction(strings.exists { x => customPredicate(x) })

this should work also with different predicate

myFunction(strings.find( _ == mystring ).isDefined)

In your case I would consider using Set and not List, to ensure you have unique values only. unless you need sometimes to include duplicates.

In this case, you don't need to add any wrapper functions around lists.

Even easier!

strings contains myString

You can also implement a contains method with foldLeft, it's pretty awesome. I just love foldLeft algorithms.

For example:

object ContainsWithFoldLeft extends App {


val list = (0 to 10).toList
println(contains(list, 10)) //true
println(contains(list, 11)) //false


def contains[A](list: List[A], item: A): Boolean = {
list.foldLeft(false)((r, c) => c.equals(item) || r)
}
}