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
Scala
Scala
// 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)
}
}
Output:
Here, keySet method is utilized.
Example #2:
Set(3, 4, 2)
// 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)
}
}
Output:
Here, keys method is utilized.
Example #3:
Set(3, 4, 2)
// 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)
}
}
Output:
Here, keysIterator method is utilized.
non-empty iterator