Open In App

How to get all the values from a Scala map

In order to get all the values from a Scala map, we need to use values method (to get all the values as an Iterable) and if we want to get the values as an iterator, we need to use valuesIterator method. Now, lets check some examples.
Example #1:




// Scala program of values()
// method
  
// Creating object
object GfG
  
    // Main method
    def main(args:Array[String])
    {
      
        // Creating a map
        val m1 = Map(3 -> "geeks", 4 -> "for", 2 -> "cs")
          
        // Applying values method
        val result = m1.values
          
        // Displays output
        println(result)
      
    }
}

Output:
MapLike(geeks, for, cs)

Here, values method is utilized.
Example #2:




// Scala program of valuesIterator()
// method
  
// Creating object
object GfG
  
    // Main method
    def main(args:Array[String])
    {
      
        // Creating a map
        val m1 = Map(3 -> "geeks", 4 -> "for", 2 -> "cs")
          
        // Applying valuesIterator method
        val result = m1.valuesIterator
          
        // Displays output
        println(result)
      
    }
}

Output:
non-empty iterator

Here, valuesIterator method is utilized.


Article Tags :