Hello how could i do this better
# codereview
a
Hello how could i do this better
is this better?
m
You can further simplify this by providing just the key selector to associateBy and avoid referencing the concrete implementation:
Copy code
val mapSomeDTO = getSomeDTOList().associateBy { it.id }
a
hello @Matteo Mirk good morning, thx for aswering
but i want a hashmap
m
why do you need to reference the concrete class instead of its interface?
in general you should prefer coupling to interfaces instead of implementations, but if you really have some reason for it, just use the other associateByTo overload
Copy code
val hashMapSomeDTO = getSomeDTOList().associateByTo(HashMap()) { it.id }
a
What i really want is returning a map because later i have to used for complete another response, in order to do not use a find on a list i rather a hashmap, but really i want to decrease from O(n^2) to O(n)
m
I see, so there’s no reason to couple the client code to a specific implementation (HashMap), you can safely return a
Map
reference if all you need is a fast lookup by id. [By the way, a linear search on a list has an average complexity of O(n), but you can use a binary search which is O(log n)]
a
yes for sure but elements on list are not ordered
m
Ah yes, sorry I overlooked that. Anyway you don’t start from O(n^2) complexity