Scala check if an item is in the list

I need to check if a string is in the list and call a function that takes a boolean accordingly.

Can this be achieved with a single 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 am sure that this can be done with less coding, but I do not know how to do this.

+73
string list scala find
Jan 10 '13 at 21:30
source share
6 answers

Just use contains

 myFunction(strings.contains(myString)) 
+106
Jan 10 '13 at
source share

And if you do not want to use strict equality, you can use exists:

 myFunction(strings.exists { x => customPredicate(x) }) 
+29
Jan 10 '13 at 22:32
source share

Even easier!

 strings contains myString 
+8
Jan 22 '18 at 11:57
source share

this should work with another predicate as well

 myFunction(strings.find( _ == mystring ).isDefined) 
+2
Jul 20 '15 at 14:38
source share

In your case, I would consider using Set rather than List to make sure that you only have unique values. if you don’t need to include duplicates sometimes.

In this case, you do not need to add any wrapper functions around the lists.

+2
04 Oct '15 at 8:45
source share

You can also implement the contains method with foldLeft , which is 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) } } 
-2
Feb 06 '19 at 9:16
source share



All Articles