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

297
Views
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 answers
Answer question

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 Report

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 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!