Scala Check if the List Contains an Element

1. Introduction

Checking if a list contains a specific element is a common operation in Scala. It's a fundamental part of list manipulation, often used in filtering, validation, or conditional logic. Scala provides a straightforward and concise way to perform this check. In this blog post, we will demonstrate how to check if a Scala list contains a particular element.

2. Program Steps

1. Create a Scala list with some elements.

2. Use the contains method to check if the list contains a specific element.

3. Print the result to verify if the element is present in the list.

4. Execute the code to observe how the contains method works in Scala.

3. Code Program

object ListContainsDemo extends App {
  val fruits = List("Apple", "Banana", "Cherry")

  // Checking if the list contains 'Banana'
  val containsBanana = fruits.contains("Banana")
  println(s"Does the list contain 'Banana'? $containsBanana")

  // Checking if the list contains 'Grape'
  val containsGrape = fruits.contains("Grape")
  println(s"Does the list contain 'Grape'? $containsGrape")
}

Output:

Does the list contain 'Banana'? true
Does the list contain 'Grape'? false

Explanation:

1. We define a list named fruits containing three elements: "Apple", "Banana", and "Cherry".

2. The contains method is used to check if 'Banana' is in the fruits list. Since 'Banana' is present, the method returns true.

3. We then use the contains method to check for 'Grape', which is not in the list. Therefore, the method returns false.

4. The results are printed, showing the boolean outcome of each contains method call.


Comments