How to create key value dictionary in Scala

2 Answers

0 votes
object MyClass {
    def main(args: Array[String]): Unit = {
        val dict = Map(2 -> "scala", 4 -> "c", 7 -> "c++", 9 -> "java")

        println(f"Key - Values: ${dict.mkString(", ")}%s")
        println(f"Key - Values: ${dict.toList.mkString(", ")}%s")
        println(f"Keys: ${dict.keys.mkString(", ")}%s")
        println(f"Values: ${dict.values.mkString(", ")}%s")   
    }
}



/*
run:

Key - Values: 2 -> scala, 4 -> c, 7 -> c++, 9 -> java
Key - Values: (2,scala), (4,c), (7,c++), (9,java)
Keys: 2, 4, 7, 9
Values: scala, c, c++, java

*/

 



answered Dec 11, 2022 by avibootz
0 votes
object MyClass {
    def main(args: Array[String]): Unit = {
        val dict = Map(2 -> "scala", 4 -> "c", 7 -> "c++", 9 -> "java")

        dict.keys.foreach{ i =>  
            print("Key = " + i)
            println(" Value = " + dict(I)) }
    }
}



/*
run:

Key = 2 Value = scala
Key = 4 Value = c
Key = 7 Value = c++
Key = 9 Value = java

*/

 



answered Dec 11, 2022 by avibootz
...