SortedMap filter() Method in Scala with Example

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

Parameter: It is the condition used to filter elements.

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


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.