https://kotlinlang.org logo
#announcements
Title
# announcements
s

Shawn

08/30/2019, 11:41 PM
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

ushort

08/31/2019, 3:56 AM
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

karelpeeters

08/31/2019, 8:22 AM
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

ushort

09/02/2019, 6:02 PM
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

karelpeeters

09/02/2019, 10:55 PM
That has even worse performance though,
fold { find { contains } }
!