Scala check if element is present in a list

StringListScalaFind

String Problem Overview


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!

String Solutions


Solution 1 - String

Just use contains

myFunction(strings.contains(myString))

Solution 2 - String

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


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

Solution 3 - String

Even easier!

strings contains myString

Solution 4 - String

this should work also with different predicate

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

Solution 5 - String

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.

Solution 6 - String

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDario OddeninoView Question on Stackoverflow
Solution 1 - StringKim StebelView Answer on Stackoverflow
Solution 2 - StringMatt HughesView Answer on Stackoverflow
Solution 3 - StringTaylrlView Answer on Stackoverflow
Solution 4 - StringDanieleDMView Answer on Stackoverflow
Solution 5 - StringguykaplanView Answer on Stackoverflow
Solution 6 - StringJohnnyView Answer on Stackoverflow