Created
September 3, 2018 20:35
-
-
Save AmineSagaama/19633917a2560ca01aa7ba19c6ad7163 to your computer and use it in GitHub Desktop.
How to traverse a Map in Scala with foreach
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
val items = Map("A" -> 100, "B" -> 200, "C" -> 300, "D" -> 400, "E" -> 500, "F" -> 600) | |
// The following approach shows how to use the Tuple syntax to display the key and value of each item | |
//Output : key: E, value: 500 key: F, value: 600 key: A, value: 100 key: B, value: 200 key: C, value: 300 key: D, value: 400 | |
items.foreach(item => println(s"key: ${item._1}, value: ${item._2}")) | |
// To display the list of keys in the Map | |
//Output : E F A B C D | |
items.keys.foreach(println) | |
// To display the list of values in the Map | |
// Output : 500 600 100 200 300 400 | |
items.values.foreach(println) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment