I have a `List<*> that I want to make a map ...
# announcements
s
I have a `List<*> that I want to make a map out of based on the objects
id
. These `id`s are unique. I know I can use
groupBy
to create a map but that results in
Map<Long, List<*>>
when I would much rather have
Map<Long, *>
. Is there a nice idiomatic way to do this in K?
c
listOfObjects.mapTo(mutableListOf()) { it.id to it }.toMap()
Silly me, this:
listOfObjects.map { it.id to it }.toMap()
s
Thanks dude! @natpryce already tipped me off to
associateBy
which is actually the most optimal solution I think.
n
i think the correct function for this is
list.associate { it.id to it }
associateBy is skipping the value part i think.. so i probably makes this even shorter
g
yes, associateBy is the shortest and most idiomatic way:
Copy code
list.associateBy { it.id }
c
Uh, missed that one, thanks 🙂