is there any kind of multi-key `associate { }` fun...
# announcements
s
is there any kind of multi-key
associate { }
function that I’m missing? I’m trying to build a map and have multiple keys associated with the objects I’m iterating over - currently I’ve got something like this:
Copy code
entries.flatMap { entry ->
      (entry.aliases + entry.name).map { it to entry }
}.toMap()
which probably isn’t the most efficient approach 😬
u
Honestly, not sure what type entries is but I'm guessing you want something similar to
Copy code
entries.associateBy( {it.name to it.aliases}, {it} )
k
No his example code maps the key
entry.name
and the keys
entry.aliases
all to the same value
entry
.
👆 1
I can't come up with anything better either 😕
😔 1
u
Hmm, do you want a list of strings as key with the entry as the value or do you want all strings in list to be a separate key. If its the former, then
entries.associateBy { it.keys }
If you meant the latter then I guess,
Copy code
entries.fold(emptyList<String>()) { sum, element ->
        sum + element.keys
    }.associateWith { key -> entries.find { entry -> entry.keys.contains(key) } }
also
Copy code
data class Entry(val name: String, val aliases: List<String>) {
        val keys = (listOf(name) + aliases).toSet()
    }
k
That has even worse performance though,
fold { find { contains } }
!