Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

488
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda