ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

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)
ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.