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:
// Scala program of keySet() // method // Creating object object GfG
{ // Main method
def main(args : Array[String])
{
// Creating a map
val m 1 = Map( 3 - > "geeks" , 4 - > "for" , 2 - > "cs" )
// Applying keySet method
val result = m 1 .keySet
// Displays output
println(result)
}
} |
Output:
Set(3, 4, 2)
Here, keySet method is utilized.
Example #2:
// Scala program of keys() // method // Creating object object GfG
{ // Main method
def main(args : Array[String])
{
// Creating a map
val m 1 = Map( 3 - > "geeks" , 4 - > "for" , 2 - > "cs" )
// Applying keys method
val result = m 1 .keys
// Displays output
println(result)
}
} |
Output:
Set(3, 4, 2)
Here, keys method is utilized.
Example #3:
// Scala program of keysIterator() // method // Creating object object GfG
{ // Main method
def main(args : Array[String])
{
// Creating a map
val m 1 = Map( 3 - > "geeks" , 4 - > "for" , 2 - > "cs" )
// Applying keysIterator method
val result = m 1 .keysIterator
// Displays output
println(result)
}
} |
Output:
non-empty iterator
Here, keysIterator method is utilized.