How to iterate over map in Scala

2 Answers

0 votes
object MyClass {
    def main(args: Array[String]): Unit = {
        val mp = Map("scala" -> 4, "php" -> 2, "c++" -> 7, "python" -> 3, "java" -> 8);
         
        for ((k, v) <- mp) 
            printf("key: %s value: %d\n", k, v);
    }
}
   
   
   
   
/*
run:
   
key: java value: 8
key: c++ value: 7
key: php value: 2
key: scala value: 4
key: python value: 3
   
*/

 



answered Jun 2, 2021 by avibootz
0 votes
object MyClass {
    def main(args: Array[String]): Unit = {
        val mp = Map("scala" -> 4, "php" -> 2, "c++" -> 7, "python" -> 3, "java" -> 8);
          
        mp.keys.foreach{ i =>  
         print("Key: " + i );
         println(" Value: " + mp(i));}
    }
}
    
    
    
    
/*
run:
    
Key: java Value: 8
Key: c++ Value: 7
Key: php Value: 2
Key: scala Value: 4
Key: python Value: 3
    
*/

 



answered Jun 2, 2021 by avibootz

Related questions

3 answers 424 views
3 answers 261 views
261 views asked Mar 3, 2025 by avibootz
1 answer 228 views
3 answers 335 views
1 answer 190 views
3 answers 335 views
...