How to get all the keys from a Scala map

In order to get all the keys from a Scala map, we need to use either keySet method (to get all the keys as a set) or we can use keys method and if you want to get the keys as an iterator, you need to use keysIterator method. Now, lets check some examples.
Example #1:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Scala program of keySet()
// 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 keySet method
        val result = m1.keySet
          
        // Displays output
        println(result)
      
    }
}

chevron_right


Output:

Set(3, 4, 2)

Here, keySet method is utilized.
Example #2:



filter_none

edit
close

play_arrow

link
brightness_4
code

// Scala program of keys()
// 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 keys method
        val result = m1.keys
          
        // Displays output
        println(result)
      
    }
}

chevron_right


Output:

Set(3, 4, 2)

Here, keys method is utilized.
Example #3:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Scala program of keysIterator()
// 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 keysIterator method
        val result = m1.keysIterator
          
        // Displays output
        println(result)
      
    }
}

chevron_right


Output:

non-empty iterator

Here, keysIterator method is utilized.



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.