Home »
Scala
SortedMap filter() Method in Scala
By IncludeHelp Last updated : November 14, 2024
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 filter() Method
SortedMap filter() method is used to select all the elements from SortedMap based on the given condition. The method returns a sortedMap which consists of elements that satisfies the given condition.
Syntax
SortedMap_Name.filter(condition)
Parameters
It is the condition used to filter elements.
Return Type
It returns a SortedMap which contains all elements that satisfy the given condition.
Example 1
When one or more elements of the SortedMap satisfy the filter condition
// Program to illustrate the working of filter method in Scala
import scala.collection.SortedMap
object myObject {
def main(args: Array[String]): Unit = {
val mySortedMap = SortedMap("scala" -> 5, "python" -> 2, "C/C++" -> 1, "JavaScript" -> 6, "Ruby" -> 8)
println("The Sorted Map is " + mySortedMap)
val filteredMap = mySortedMap.filter(ele => ele._2 > 3)
println(filteredMap)
}
}
Output
The Sorted Map is TreeMap(C/C++ -> 1, JavaScript -> 6, Ruby -> 8, python -> 2, scala -> 5)
TreeMap(JavaScript -> 6, Ruby -> 8, scala -> 5)
Example 2
When no elements of the SortedMap satisfy the filter condition
// Program to illustrate the working of filter() method in scala
import scala.collection.SortedMap
object myObject {
def main(args: Array[String]): Unit = {
val mySortedMap = SortedMap("scala" -> 5, "python" -> 2, "C/C++" -> 1, "JavaScript" -> 6, "Ruby" -> 8)
println("The Sorted Map is " + mySortedMap)
val filteredMap = mySortedMap.filter(ele => ele._2 == 3)
println(filteredMap)
}
}
Output
The Sorted Map is TreeMap(C/C++ -> 1, JavaScript -> 6, Ruby -> 8, python -> 2, scala -> 5)
TreeMap()