How to iterate over a collection of key-value pairs (associative array) in Scala

5 Answers

0 votes
// Simple for loop with pattern matching

object Main {
    def main(args: Array[String]) = {
        val map = Map("d" -> 4, "a" -> 1, "c" -> 3, "b" -> 2)
        
        for ((key, value) <- map) {
          println(s"$key = $value")
        }
    }
}



/*
run:

d = 4
a = 1
c = 3
b = 2

*/

 



answered Mar 23 by avibootz
0 votes
// Using foreach with a tuple pattern

object Main {
    def main(args: Array[String]) = {
        val map = Map("d" -> 4, "a" -> 1, "c" -> 3, "b" -> 2)
        
        map.foreach { case (key, value) =>
          println(s"$key = $value")
        }
    }
}



/*
run:

d = 4
a = 1
c = 3
b = 2

*/

 



answered Mar 23 by avibootz
0 votes
// Iterate over keys only

object Main {
    def main(args: Array[String]) = {
        val map = Map("d" -> 4, "a" -> 1, "c" -> 3, "b" -> 2)
        
        for (key <- map.keys) {
          println(s"Key: $key")
        }
    }
}



/*
run:

Key: d
Key: a
Key: c
Key: b

*/

 



answered Mar 23 by avibootz
0 votes
// Iterate over keys + lookup

object Main {
    def main(args: Array[String]) = {
        val map = Map("d" -> 4, "a" -> 1, "c" -> 3, "b" -> 2)
        
        for (key <- map.keys) {
          println(s"$key = ${map(key)}")
        }
    }
}



/*
run:

d = 4
a = 1
c = 3
b = 2

*/

 



answered Mar 23 by avibootz
0 votes
// Iterate over values only

object Main {
    def main(args: Array[String]) = {
        val map = Map("d" -> 4, "a" -> 1, "c" -> 3, "b" -> 2)
        
        for (value <- map.values) {
          println(value)
        }
    }
}



/*
run:

4
1
3
2

*/

 



answered Mar 23 by avibootz

Related questions

...