Scala Map and foreach

Category : Scala | Sub Category : Scala Programs | By Prasad Bonam Last updated: 2020-10-10 03:54:36 Viewed : 505


Scala Map and foreach  

In Scala, a Map is a collection that stores key-value pairs. You can use a Map to associate each key with a value and then retrieve the value by specifying the key. The foreach method is used to iterate over the key-value pairs in a Map and apply a function to each pair. Here is how you can use Map and foreach:

1. Creating a Map:

You can create a Map in Scala using various methods. Here is one way to create a Map:

scala
val myMap = Map("Alice" -> 25, "Bob" -> 30, "Carol" -> 28)

In this example, we create a Map named myMap with key-value pairs representing ages.

2. Iterating Over a Map (Using foreach):

You can use the foreach method to iterate over the key-value pairs in a Map:

scala
myMap.foreach { case (name, age) => println(s"$name is $age years old") }

In this code, we iterate over each key-value pair in the myMap and print a message with the name and age.

3. Output:

Here is how you can print the results:

scala
println("My Map:") myMap.foreach { case (name, age) => println(s"$name is $age years old") }

4. Complete Example:

Putting it all together:

scala
val myMap = Map("Alice" -> 25, "Bob" -> 30, "Carol" -> 28) println("My Map:") myMap.foreach { case (name, age) => println(s"$name is $age years old") }

Output:

csharp
My Map: Alice is 25 years old Bob is 30 years old Carol is 28 years old

In this example, we create a Map with key-value pairs, use foreach to iterate over the pairs, and print a message for each key-value pair, demonstrating how to work with Map and foreach in Scala.


Use Maps to look up values with keys. Create a Map and invoke Map functions.

def apply[A, B](elems: (A, B)*): Map[A, B]

A collection of type Map that contains given key/value bindings.

the key/value pairs that make up the map 

Example 1:

Following example illustrates about Scala Map initilization

Save the file as −  ScalaMap.scala. 

ScalaMap.scala

 package runnerdev

/** Scala program that creates Map*/

object ScalaMap extends App { 

  // Use simple map initialization syntax.

  val weights = Map("cat" -> 9"dog" -> 60) 

  // Look up animal weights.

  val weight = weights("dog")

  println("weight "+weight) 

}

 compile and run the above example as follows 

scala> scalac ScalaMap.scala

scalascala ScalaMap 

Output:

Weight 60

  Example 2:

Following example illustrates about Scala creates Map with pair

Save the file as −  ScalaMap1.scala. 

ScalaMap1.scala 

 package runnerdev

/**Scala program that creates Map with pair syntax */

object ScalaMap1 extends App {

  // Create map of animals to colors.

  // ..Has string keys and string values.

  val colors = Map(("cat""white"), ("dog""red")) 

  // Get value for this key.

  val result1 = colors("cat")

  println(result1) 

  val result2 = colors("dog")

  println(result2)

}

 

compile and run the above example as follows 

scala> scalac ScalaMap1.scala

scalascala ScalaMap1 

Output:

white

red

 Example 3:

Following example illustrates about Scala adds key, value to Map

Save the file as −  ScalaMap2.scala

ScalaMap2.scala  

 package runnerdev

/** Scala program that adds key, value to map **/

object ScalaMap2 extends App {

  // Create an immutable map.

  val animal = Map("cat" -> 1"dog" -> 1)

  println(animal)

  // Add a pair to the map.

  //  This creates a new map.

  val all = animal + ("lion" -> 1)

  println(all)

}

 compile and run the above example as follows 

scala> scalac ScalaMap2.scala

scalascala ScalaMap2 

Output:

Map(cat -> 1, dog -> 1)

Map(cat -> 1, dog -> 1, lion -> 1)  

Example 4:

Applies a function f to all elements of this iterable collection

def foreach[U](f: String => U): Unit 

Collects all keys of this map in an iterable collection.

def keys: Iterable[String] 

Following example illustrates about Scala gets keys, values from Map

Save the file as −  ScalaMap3.scala 

 ScalaMap3.scala  

 package runnerdev

/** Scala program that gets keys, values   **/

object ScalaMap3 extends App {

  // Create map of String keys and Int values.

  val ids = Map(("One"1), ("Two"2)) 

  // Use foreach function to print each key.

  ids.keys.foreach(println(_)) 

  // Use for-loop to iterate over all values.

  for (value <- ids.values) {

    println(value)

  }

}

compile and run the above example as follows 

scala> scalac ScalaMap3.scala

scalascala ScalaMap3 

Output:

One

Two

1

2

 

Example 5:

·        Optionally returns the value associated with a key.

def get(key: String): Option[Int] 

·        Returns the value associated with a key, or a default value if the key is not contained in the map.

def getOrElse[V1 >: Int](key: String, default: => V1): V1 

·        The size of this immutable map.

def size: Int 

·        Returns true if the option is an instance of scala.Some, false otherwise.

def isDefined: Boolean 

·        The same map with a given default value. Note: getcontainsiteratorkeys, etc are not affected by withDefaultValue.

def withDefaultValue[V1 >: Int](d: V1): Map[String, V1] 

·        Class Some[A] represents existing values of type A.

scala.Some 

Following example illustrates about Scala program that uses get ,getOrElse  and isDefined

Save the file as −  ScalaMap4.scala 

  ScalaMap4.scala 

 package runnerdev

/** Scala program that uses get, getOrElse  **/

object ScalaMap4 extends App {

  // Create a String, Int map.

  val map = Map(("Blue"2), ("Red"4))

  println("mapSize " + map.size//2 

  // This key does not exist, so the option is not defined.

  val resultMap1 = map.get("Pink")

  if (!resultMap1.isDefined) {

    println("Not exist")

  } 

  // This key exists... Get and print the options internal value.

  val resultMap2 = map.get("Red")

  if (resultMap2.isDefined) {

    println(resultMap2//Some(4)

    val number = resultMap2.get

    println(number//4

  } 

  // Use a default value if the key does not exist.

  val result3 = map.getOrElse("Pink"0)

  if (result3 == 0) {

    println("Zero, else value")

  } 

  //Scala program that uses withDefaultValue

  val animalMap = Map(("cat"9), ("dog"5)) 

  // The default value is now negative 1.

  val animalMapDefault = animalMap.withDefaultValue(-1); 

  // Use map with default.

  val result1 = animalMapDefault("cat")

  println(result1//9 

  val result2 = animalMapDefault("bear")

  println(result2//-1 

}


compile and run the above example as follows 

scala> scalac ScalaMap4.scala

scalascala ScalaMap4 

Output:

mapSize 2

Not exist

Some(4)

4

Zero, else value

9

-1

Search
Related Articles

Leave a Comment: