×

Scala Tutorial

Scala Basics

Scala Control statements

Scala Functions

Scala Arrays

Scala Lists

Scala Strings

Scala Classes & Objects

Scala Collections

How to concatenate two maps in Scala?

By IncludeHelp Last updated : November 16, 2024

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.

Concatenating Two Maps

The concatenation operation is performed using ++ operator.

Syntax

map1 .++ (map2)

Parameters

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

Return Value

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]): Unit = {
        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]): Unit = {
        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.