How to concatenate two maps in Scala?

Here, we are going to learn how to concatenate two maps in Scala?
Submitted by Shivang Yadav, on January 07, 2021

A map is a collection that stores its elements as key-value pairs, like a dictionary. Also, known as hash tables, maps have unique keys that are used to retrieve the value related to the key.

There might be times in programming when you need to merge two maps into one for processing. And Scala provides you a method to concatenate two maps to one map in Scala.

The concatenation operation is performed using ++ operator.

Syntax:

map1 .++ (map2)

Parameters: It accepts a single parameter which is the map to be concatenated.

Returns: It returns a map which is the concatenated map of both the maps.

Program to illustrate the working of concatenation operation

object MyClass {
    def main(args: Array[String]) {
        val map1 = Map(1 -> "C/C++", 5 -> "Java")
        val map2 = Map(2 -> "Python", 8 -> "Scala")
        
        println("Map1 : " + map1)
        println("Map2 : " + map2)
        
        // concatenating maps 
        val concMap = map1 .++ (map2)
        println("Concatenated Map : " + concMap)
    }
}

Output:

Map1 : Map(1 -> C/C++, 5 -> Java)
Map2 : Map(2 -> Python, 8 -> Scala)
Concatenated Map : Map(1 -> C/C++, 5 -> Java, 2 -> Python, 8 -> Scala)

Program to illustrate the working of map concatenation in Scala

Here, we have a common element in both maps, which will be taken only once while concatenating.

object MyClass {
    def main(args: Array[String]) {
        val map1 = Map(1 -> "C/C++", 5 -> "Java")
        val map2 = Map(5 -> "Java", 8 -> "Scala")
        
        println("Map1 : " + map1)
        println("Map2 : " + map2)
        
        // concatenating maps 
        val concMap = map1 .++ (map2)
        println("Concatenated Map : " + concMap)
    }
}

Output:

Map1 : Map(1 -> C/C++, 5 -> Java)
Map2 : Map(5 -> Java, 8 -> Scala)
Concatenated Map : Map(1 -> C/C++, 5 -> Java, 8 -> Scala)


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.