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




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.