Scala check if element is present in a list

2020-05-14 13:19发布

问题:

I need to check if a string is present in a list, and call a function which accepts a boolean accordingly.

Is it possible to achieve this with a one liner?

The code below is the best I could get:

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

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

I'm sure it's possible to do this with less coding, but I don't know how!

回答1:

Just use contains

myFunction(strings.contains(myString))


回答2:

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


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


回答3:

Even easier!

strings contains myString


回答4:

this should work also with different predicate

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


回答5:

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.



回答6:

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)
  }
}