Home »
Scala
SortedMap exists() Method in Scala with Example
In this tutorial, we will learn about exists() method of SortedMap class. It is used to check whether the elements of SortedMap satisfy the given condition. We will learn about exists() method with examples.
Submitted by Shivang Yadav, on December 20, 2020
Map is a collection that stores its elements as key-value pairs, like a dictionary. SortedMap is a special type of map in which elements are sorted in ascending order.
SortedMap exists() Method
exists(): The exists() method on SortedMap is used to check if any of the elements of the sortedMap satisfy the given condition.
Syntax:
SortedMap_Name.exists(condition)
Parameter: It accepts a condition that will satisfy the SortedMap.
Return: It returns a boolean value based on the condition. If any elements satisfy the condition, it returns true else false.
Example 1: Illustrate the working of SortedMap exists() method
// Program to illustrate the working of exists() method in scala
import scala.collection.SortedMap
object myObject {
def main(args: Array[String]) {
val mySortedMap = SortedMap("scala" -> 5, "python" -> 2, "C/C++" -> 1)
println("The Sorted Map is " + mySortedMap)
val result = mySortedMap.exists(ele => ele._1 == "scala" && ele._2 == 5)
if(result)
println("The value exists in the map")
else
println("The value does not exists in the map")
}
}
Output:
The Sorted Map is TreeMap(C/C++ -> 1, python -> 2, scala -> 5)
The value exists in the map
Example 2:
// Program to illustrate the working of exists() method in Scala
import scala.collection.SortedMap
object myObject {
def main(args: Array[String]) {
val mySortedMap = SortedMap("scala" -> 5, "python" -> 2, "C/C++" -> 1)
println("The Sorted Map is " + mySortedMap)
val result = mySortedMap.exists(ele => ele._1 == "java" && ele._2 == 3)
if(result)
println("The value exists in the map")
else
println("The value does not exist in the map")
}
}
Output:
The Sorted Map is TreeMap(C/C++ -> 1, python -> 2, scala -> 5)
The value does not exist in the map