Home »
Scala
SortedMap filterKeys() 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 filterKeys() Method
SortedMap filterKeys() method is used to select all the elements from SortedMap whose keys satisfy the given condition. It returns the filtered SortedMap based on the condition on keys.
It is similar to filter() method that we have seen in the last article.
Syntax
SortedMap_Name.filterKeys(key_condition)
Parameters
It accepts a single parameter which is the condition for keys to filter the map elements.
Return Type
It returns a SortedMap which consist of filter elements from the SortedMap.
Example 1
When one or more elements of the SortedMap satisfy the given condition
// Program to illustrate the working of filterKeys() method in Scala
import scala.collection.SortedMap
object myObject {
def main(args: Array[String]): Unit = {
val mySortedMap = SortedMap(1 -> "Delhi", 2 -> "Mumbai", 8 -> "Hyderabad" , 11 -> "Indore")
println("The Sorted Map is " + mySortedMap)
val filteredMap = mySortedMap.filterKeys(_ < 3)
println(filteredMap)
}
}
Output
The Sorted Map is TreeMap(1 -> Delhi, 2 -> Mumbai, 8 -> Hyderabad, 11 -> Indore)
TreeMap(1 -> Delhi, 2 -> Mumbai)
Example 2
When no element satisfies the filter condition
// Program to illustrate the working of filterKeys() method in Scala
import scala.collection.SortedMap
object myObject {
def main(args: Array[String]): Unit = {
val mySortedMap = SortedMap(1 -> "Delhi", 2 -> "Mumbai", 8 -> "Hyderabad" , 11 -> "Indore")
println("The Sorted Map is " + mySortedMap)
val filteredMap = mySortedMap.filterKeys(_ == 3)
println(filteredMap)
}
}
Output
The Sorted Map is TreeMap(1 -> Delhi, 2 -> Mumbai, 8 -> Hyderabad, 11 -> Indore)
TreeMap()