SortedMap filterKeys() Method in Scala with Example

In this tutorial, we will learn about filterKeys() method of SortedMap class. It is used to check to select the elements of SortedMap where the keys satisfy the given condition. We will learn about filterKeys() 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 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)

Parameter: It accepts a single parameter which is the condition for keys to filter the map elements.

Return: 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]) {
        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]) {
        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()




Comments and Discussions




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.