Scala SortedMap max() Method with Example

Here, we will learn about the max() method of SortedMap class in Scala. We will see its working, syntax and examples.
Submitted by Shivang Yadav, on February 08, 2021

Map is a collection that stores its elements as key-value pairs, like a dictionary. Also, known as hash tables, maps have unique keys that are used to retrieve the value related to the key.

SortedMap max() Method

The max() method on SortedMap in Scala is used to find the maximum element of the SortedMap.

Syntax:

sortedMapName.max()

Parameters: This method is a parameter-less method i.e., it does not accept any parameter.

Return: The method returns the largest element of the SortedMap. This element is the one with the largest key value in the map.

Example 1:

import scala.collection.immutable.SortedMap

object myObject {
    def main(args: Array[String]) {
        var myMap = SortedMap(1 -> "Scala", 3 -> "Java", 9 -> "JavaScript", 4 -> "C++")
        println("The contents of sorted Map are " + myMap)
        
        val maxEle = myMap.max
        println("The largest element of the sorted Map is " + maxEle)
    }       
}

Output:

The contents of sorted Map are TreeMap(1 -> Scala, 3 -> Java, 4 -> C++, 9 -> JavaScript)
The largest element of the sorted Map is (9,JavaScript)

Example 2:

import scala.collection.immutable.SortedMap

object myObject {
    def main(args: Array[String]) {
        var myMap = SortedMap(1 -> "Scala", 3 -> "Java", 9 -> "JavaScript", 4 -> "C++", 9 -> "Python")
        println("The contents of sorted Map are " + myMap);
        
        val maxEle = myMap.max
        println("The largest element of the sorted Map is " + maxEle)    
    }       
}

Output:

The contents of sorted Map are TreeMap(1 -> Scala, 3 -> Java, 4 -> C++, 9 -> Python)
The largest element of the sorted Map is (9,Python)


Comments and Discussions!

Load comments ↻





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