SortedMap find() Method in Scala with Example

In this problem, we will learn about find() method in sortedMAp class. It is used to find the first occurrence of an element based on a certain condition in the sortedMap. We will learn about the find() method with examples.
Submitted by Shivang Yadav, on January 04, 2021

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 find() Method

The find() method on SortedMap is used to find the first element from the map that satisfies the given condition in the parameter of the method.



Parameter: The method accepts a condition.

Return: It returns an element that satisfies the given condition.

Example: Program to illustrate the working of find() method

import scala.collection.SortedMap

object MyClass {
    def main(args: Array[String]) {
        val mySortedMap = SortedMap("scala" -> 5, "JavaScript" -> 6, "Ruby" -> 8)
        println("Sorted Map: " + mySortedMap)
        val isPresentEle1 = mySortedMap.find(ele => ele._2 == 5)
        println("Element with value 4 present " + isPresentEle1)
        val isPresentEle2 = mySortedMap.find(ele => ele._2 == 3)
        println("Element with value 3 present " + isPresentEle2)


Sorted Map: TreeMap(JavaScript -> 6, Ruby -> 8, scala -> 5)
Element with value 4 present Some((scala,5))
Element with value 3 present None

Comments and Discussions!

Load comments ↻

Copyright © 2024 All rights reserved.