Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

490
Views
Merge nested maps with similar outer keys, keeping both inner map's key value pairs

I would like to merge two nested maps as per below, without overwriting the data of the outer map's values, or by replacing the inner map, and overwriting the data already there.

Ideally within the nested map, I would keep the key/value pairs I already have, and add to that with the second map.

    val mapOne: MutableMap<String, MutableMap<String, String>>  = mutableMapOf(
        "DirectoryOne" to  mutableMapOf(
            "FeatureOne" to "SomeUniqueStringFeature1",
            "FeatureTwo" to "SomeUniqueStringFeature2"
        )
    )
    val mapTwo: MutableMap<String, MutableMap<String, String>> = mutableMapOf(
        "DirectoryOne" to  mutableMapOf(
            "FeatureThree" to "SomeUniqueStringFeature3"
        )
    )

The result I need would look as follows:

    val mapOne: MutableMap<String, MutableMap<String, String>>  = mutableMapOf(
        "DirectoryOne" to  mutableMapOf(
            "FeatureOne" to "SomeUniqueStringFeature1",
            "FeatureTwo" to "SomeUniqueStringFeature2",
            "FeatureThree" to "SomeUniqueStringFeature3"
        )
    )

Just to elaborate some into reasoning behind this. I am planning on building the map dynamically at runtime and add features to a single map as they are required to be added throughout the duration of the application.

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

I was able to perform the desired action with the below code. Iterating over the outer key/value pairs and merging the nested key/value pairs with a BiConsumer/BiFunction to mapOne. (Typing got a bit burdensome)

mapTwo.forEach(BiConsumer { k: String, v: MutableMap<String, String> ->
        mapOne.merge(k, v,
            BiFunction { v1: MutableMap<String, String>, v2: MutableMap<String, String> ->
                v1.putAll(v2)
                v1
            })
    })

I soon discovered that I could more easily employ a lambda (Removing the BiConsumer/BiFunction) and then move the lambda out of the merge parenthesis. The final optimal solution is shown below.

mapTwo.forEach { (k: String, v: MutableMap<String, String>) ->
        mapOne.merge(k, v
        ) { v1: MutableMap<String, String>, v2: MutableMap<String, String> ->
            v1.putAll(v2)
            v1
        }
    }

I am wrapping the above snippet in a function/method to be able to apply this multiple times where needed.

over 4 years ago · Santiago Trujillo Report

0

If you want to avoid the awkward use of the Java 8 merge function, you can use getOrPut. This is also more efficient because of the function inlining.

Also, according to Kotlin coding conventions, it's preferable to use a regular for loop instead of forEach (unless you're calling it on a nullable or at the end of a chain of collection operators).

for ((key, map) in mapTwo) {
    mapOne.getOrPut(key, ::mutableMapOf).putAll(map)
}

Generalized:

fun <K1, K2, V> MutableMap<in K1, MutableMap<K2, V>>.mergeIn(other: Map<out K1, Map<out K2, V>>) {
    for ((key, map) in other) {
        getOrPut(key, ::mutableMapOf).putAll(map)
    }
}
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!