Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

298
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda