Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,656 questions

55,403 answers

573 users

How to combine 2 maps into a third map in Scala

3 Answers

0 votes
val map1 = Map("a" -> 1, "b" -> 2)
val map2 = Map("b" -> 999, "c" -> 4, "d" -> 5)

val combined = map1 ++ map2

println(combined) 


 
/*
run:
  
Map(a -> 1, b -> 999, c -> 4, d -> 5)
  
*/

 



answered Aug 26, 2025 by avibootz
0 votes
val map1 = Map("a" -> 1, "b" -> 2)
val map2 = Map("b" -> 999, "c" -> 4, "d" -> 5)

val combined = (map1.keySet ++ map2.keySet).map { key =>
  val v1 = map1.getOrElse(key, 0)
  val v2 = map2.getOrElse(key, 0)
  key -> (v1 + v2)
}.toMap

println(combined) 


 
/*
run:
  
Map(a -> 1, b -> 1001, c -> 4, d -> 5)
  
*/

 



answered Aug 26, 2025 by avibootz
0 votes
val map1 = Map("a" -> 1, "b" -> 2)
val map2 = Map("b" -> 999, "c" -> 4, "d" -> 5)

val combined = map2.foldLeft(map1) {
  case (acc, (key, value)) =>
    acc.updated(key, acc.getOrElse(key, 0) + value)
}

println(combined) 


 
/*
run:
  
Map(a -> 1, b -> 1001, c -> 4, d -> 5)
  
*/

 



answered Aug 26, 2025 by avibootz

Related questions

1 answer 134 views
1 answer 112 views
3 answers 159 views
1 answer 110 views
3 answers 281 views
...