103

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!

Dario Oddenino
  • 1,294
  • 2
  • 9
  • 15

6 Answers6

145

Just use contains

myFunction(strings.contains(myString))
Kim Stebel
  • 41,826
  • 12
  • 125
  • 142
  • 3
    What if I don't deal with a string but I need to check if a value is any of a number of possible matches? – tutuca Apr 01 '14 at 19:00
  • 2
    @tutuca, check this [checking-if-values-in-list-is-part-of-string](http://stackoverflow.com/questions/16046146/checking-if-values-in-list-is-part-of-string). – Om Prakash Mar 03 '17 at 07:20
35

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


myFunction(strings.exists { x => customPredicate(x) })
Matt Hughes
  • 1,458
  • 2
  • 14
  • 17
23

Even easier!

strings contains myString
Taylrl
  • 3,601
  • 6
  • 33
  • 44
  • 5
    How is that different from [the accepted answer](https://stackoverflow.com/a/14267635/8371915)? – Alper t. Turker Jan 22 '18 at 14:03
  • 6
    It's fundamentally the same but differences are: 1. Fewer brackets 2. Fewer periods 3. No reference to myFunction 4. more white space. Overall; My answer = 25 characters vs Accepted answer = 38 characters – Taylrl Jan 22 '18 at 14:07
  • It was a rhetoric question ;) To give you a context I got here from [LQP](https://stackoverflow.com/review/low-quality-posts/). I didn't recommend deletion, but if you post late answer try provide some additional value. A bit of syntactic sugar it doesn't feel like it, you know. Just saying... – Alper t. Turker Jan 22 '18 at 14:13
  • 4
    No problems. I understand. I think it does add value by showing increased simplicity. Thanks anyway though :) – Taylrl Jan 22 '18 at 21:33
3

this should work also with different predicate

myFunction(strings.find( _ == mystring ).isDefined)
DanieleDM
  • 1,762
  • 2
  • 16
  • 13
2

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.

guykaplan
  • 145
  • 1
  • 3
-1

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)
  }
}
Johnny
  • 14,397
  • 15
  • 77
  • 118