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

299
Vistas
Compose maps using key and value in Kotlin

I have two maps and I want to merge using some rules

val a = mapOf(1 to 101, 2 to 102, 3 to 103)
val b = mapOf(101 to "a", 102 to "b", 103 to "c")

is there a way to merge using values for a and key for b

val result = mapOf(1 to "A", 2 to "b", 3 to "c")
over 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

Since you're sure each value from map a is present in map b, this should be as simple as using mapValues and using the value of that key in map b

a.mapValues { entry ->
    b[entry.value]
}

Due to having to edit and redo my answer, @Sweeper beat me to it and provided a more in-depth answer.

over 4 years ago · Santiago Trujillo Denunciar

0

Since the values of a and the keys of b will always match, you can do this with a single mapValues, with the !! being safe:

val result = a.mapValues { (_, v) -> b[v]!! }

If you hate the appearance of !!, you can replace that with

?: error("some appropriate error message")

Since it is assumed that b will always have the values of a as the key.

In general, if b may not have all the values of a as keys, you can do:

val result = a.entries.mapNotNull { (k, v) -> b[v]?.let { k to it } }.toMap()

This removes the key from the result, if the key's corresponding value in a doesn't exist as a key in b. You can also use this as an alternative if you don't like the !! in the first solution.

mapNotNull and toMap loops through the entries one time each. If that is a problem for you, use asSequence:

a.asSequence().mapNotNull { (k, v) -> b[v]?.let { k to it } }.toMap()
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